crypto for refreshing

This commit is contained in:
Florian Dold 2016-10-12 23:30:10 +02:00
parent d4be3906e3
commit 122e069d91
6 changed files with 351 additions and 124 deletions

View File

@ -1,6 +1,6 @@
// Place your settings in this file to overwrite default and user settings.
{
// Use latest language services
// Use latest language servicesu
"typescript.tsdk": "node_modules/typescript/lib",
// Defines space handling after a comma delimiter
"typescript.format.insertSpaceAfterCommaDelimiter": true,
@ -33,5 +33,6 @@
"when": "$(basename).tsx"
},
"**/*.js.map": true
}
},
"editor.wrappingIndent": "same"
}

View File

@ -33,6 +33,8 @@ export interface EmscFunGen {
export declare namespace Module {
var cwrap: EmscFunGen;
function ccall(name: string, ret:"number"|"string", argTypes: any[], args: any[]): any
function stringToUTF8(s: string, addr: number, maxLength: number): void
function _free(ptr: number): void;

View File

@ -20,7 +20,7 @@ import * as EmscWrapper from "../emscripten/emsc";
/**
* High-level interface to emscripten-compiled modules used
* by the wallet.
* @module EmscriptIf
*
* @author Florian Dold
*/
@ -102,6 +102,15 @@ var emsc = {
random_block: getEmsc('GNUNET_CRYPTO_random_block',
'void',
['number', 'number', 'number']),
hash_context_abort: getEmsc('GNUNET_CRYPTO_hash_context_abort',
'void',
['number']),
hash_context_read: getEmsc('GNUNET_CRYPTO_hash_context_read',
'void',
['number', 'number', 'number']),
hash_context_finish: getEmsc('GNUNET_CRYPTO_hash_context_finish',
'void',
['number', 'number']),
};
var emscAlloc = {
@ -147,6 +156,9 @@ var emscAlloc = {
rsa_unblind: getEmsc('GNUNET_CRYPTO_rsa_unblind',
'number',
['number', 'number', 'number']),
hash_context_start: getEmsc('GNUNET_CRYPTO_hash_context_start',
'number',
[]),
malloc: (size: number) => Module._malloc(size),
};
@ -155,6 +167,7 @@ export enum SignaturePurpose {
RESERVE_WITHDRAW = 1200,
WALLET_COIN_DEPOSIT = 1201,
MASTER_DENOMINATION_KEY_VALIDITY = 1025,
WALLET_COIN_MELT = 1202,
}
enum RandomQuality {
@ -163,9 +176,49 @@ enum RandomQuality {
NONCE = 2
}
interface ArenaObject {
destroy(): void;
}
abstract class ArenaObject {
class HashContext implements ArenaObject {
private hashContextPtr: number | undefined;
constructor() {
this.hashContextPtr = emscAlloc.hash_context_start();
}
read(obj: PackedArenaObject): void {
if (!this.hashContextPtr) {
throw Error("assertion failed");
}
emsc.hash_context_read(this.hashContextPtr, obj.getNative(), obj.size());
}
finish(h: HashCode) {
if (!this.hashContextPtr) {
throw Error("assertion failed");
}
h.alloc();
emsc.hash_context_finish(this.hashContextPtr, h.getNative());
}
destroy(): void {
if (this.hashContextPtr) {
emsc.hash_context_abort(this.hashContextPtr);
}
this.hashContextPtr = undefined;
}
}
abstract class MallocArenaObject implements ArenaObject {
protected _nativePtr: number | undefined = undefined;
/**
* Is this a weak reference to the underlying memory?
*/
isWeak = false;
arena: Arena;
abstract destroy(): void;
@ -192,7 +245,7 @@ abstract class ArenaObject {
}
free() {
if (this.nativePtr) {
if (this.nativePtr && !this.isWeak) {
emsc.free(this.nativePtr);
this._nativePtr = undefined;
}
@ -270,7 +323,7 @@ class SyncArena extends DefaultArena {
super();
}
pub(obj: ArenaObject) {
pub(obj: MallocArenaObject) {
super.put(obj);
if (!this.isScheduled) {
this.schedule();
@ -295,7 +348,7 @@ let arenaStack: Arena[] = [];
arenaStack.push(new SyncArena());
export class Amount extends ArenaObject {
export class Amount extends MallocArenaObject {
constructor(args?: AmountJson, arena?: Arena) {
super(arena);
if (args) {
@ -399,7 +452,7 @@ export class Amount extends ArenaObject {
/**
* Count the UTF-8 characters in a JavaScript string.
*/
function countBytes(str: string): number {
function countUtf8Bytes(str: string): number {
var s = str.length;
// JavaScript strings are UTF-16 arrays
for (let i = str.length - 1; i >= 0; i--) {
@ -424,7 +477,7 @@ function countBytes(str: string): number {
* Managed reference to a contiguous block of memory in the Emscripten heap.
* Should contain only data, not pointers.
*/
abstract class PackedArenaObject extends ArenaObject {
abstract class PackedArenaObject extends MallocArenaObject {
abstract size(): number;
constructor(a?: Arena) {
@ -658,14 +711,14 @@ export class ByteArray extends PackedArenaObject {
static fromString(s: string, a?: Arena): ByteArray {
// UTF-8 bytes, including 0-terminator
let terminatedByteLength = countBytes(s) + 1;
let terminatedByteLength = countUtf8Bytes(s) + 1;
let hstr = emscAlloc.malloc(terminatedByteLength);
Module.stringToUTF8(s, hstr, terminatedByteLength);
return new ByteArray(terminatedByteLength, hstr, a);
}
static fromCrock(s: string, a?: Arena): ByteArray {
let byteLength = countBytes(s);
let byteLength = countUtf8Bytes(s);
let hstr = emscAlloc.malloc(byteLength + 1);
Module.stringToUTF8(s, hstr, byteLength + 1);
let decodedLen = Math.floor((byteLength * 5) / 8);
@ -798,6 +851,34 @@ export class WithdrawRequestPS extends SignatureStruct {
}
interface RefreshMeltCoinAffirmationPS_Args {
session_hash: HashCode;
amount_with_fee: AmountNbo;
melt_fee: AmountNbo;
coin_pub: EddsaPublicKey;
}
export class RefreshMeltCoinAffirmationPS extends SignatureStruct {
constructor(w: RefreshMeltCoinAffirmationPS_Args) {
super(w);
}
purpose() {
return SignaturePurpose.WALLET_COIN_MELT;
}
fieldTypes() {
return [
["session_hash", HashCode],
["amount_with_fee", AmountNbo],
["melt_fee", AmountNbo],
["coin_pub", EddsaPublicKey]
];
}
}
export class AbsoluteTimeNbo extends PackedArenaObject {
static fromTalerString(s: string): AbsoluteTimeNbo {
let x = new AbsoluteTimeNbo();
@ -825,7 +906,14 @@ function set64(p: number, n: number) {
Module.setValue(p + (7 - i), n & 0xFF, "i8");
n = Math.floor(n / 256);
}
}
// XXX: This only works up to 54 bit numbers.
function set32(p: number, n: number) {
for (let i = 0; i < 4; ++i) {
Module.setValue(p + (3 - i), n & 0xFF, "i8");
n = Math.floor(n / 256);
}
}
@ -843,6 +931,20 @@ export class UInt64 extends PackedArenaObject {
}
export class UInt32 extends PackedArenaObject {
static fromNumber(n: number): UInt64 {
let x = new UInt32();
x.alloc();
set32(x.getNative(), n);
return x;
}
size() {
return 8;
}
}
// It's redundant, but more type safe.
export interface DepositRequestPS_Args {
h_contract: HashCode;
@ -940,7 +1042,7 @@ function makeEncode(encodeFn: any) {
}
export class RsaPublicKey extends ArenaObject implements Encodeable {
export class RsaPublicKey extends MallocArenaObject implements Encodeable {
static fromCrock: (s: string, a?: Arena) => RsaPublicKey;
toCrock() {
@ -965,7 +1067,7 @@ export class EddsaSignature extends PackedArenaObject {
}
export class RsaSignature extends ArenaObject implements Encodeable {
export class RsaSignature extends MallocArenaObject implements Encodeable {
static fromCrock: (s: string, a?: Arena) => RsaSignature;
encode: (arena?: Arena) => ByteArray;
@ -1031,3 +1133,52 @@ export function rsaUnblind(sig: RsaSignature,
pk.nativePtr);
return x;
}
type TransferSecretP = HashCode;
export function kdf(outLength: number,
salt: PackedArenaObject,
skm: PackedArenaObject,
...contextChunks: PackedArenaObject[]): ByteArray {
const args: number[] = [];
let out = new ByteArray(outLength);
args.push(out.nativePtr, outLength);
args.push(salt.nativePtr, salt.size());
args.push(skm.nativePtr, skm.size());
for (let chunk of contextChunks) {
args.push(chunk.nativePtr, chunk.size());
}
// end terminator (it's varargs)
args.push(0);
args.push(0);
let argTypes = args.map(() => "number");
const res = Module.ccall("GNUNET_CRYPTO_kdf", "number", argTypes, args);
if (res != GNUNET_OK) {
throw Error("fatal: kdf failed");
}
return out;
}
export interface FreshCoin {
priv: EddsaPrivateKey;
blindingKey: RsaBlindingKeySecret;
}
export function setupFreshCoin(secretSeed: TransferSecretP, coinIndex: number): FreshCoin {
let priv = new EddsaPrivateKey();
priv.isWeak = true;
let blindingKey = new RsaBlindingKeySecret();
blindingKey.isWeak = true;
let buf = kdf(priv.size() + blindingKey.size(), UInt32.fromNumber(coinIndex), ByteArray.fromString("taler-coin-derivation"));
priv.nativePtr = buf.nativePtr;
blindingKey.nativePtr = buf.nativePtr + priv.size();
return { priv, blindingKey };
}

View File

@ -14,7 +14,6 @@
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
/**
* Smaller helper functions that do not depend
* on the emscripten machinery.
@ -22,7 +21,10 @@
* @author Florian Dold
*/
/// <reference path="../decl/urijs/URIjs.d.ts" />
import {AmountJson} from "./types";
import URI = uri.URI;
export function substituteFulfillmentUrl(url: string, vars: any) {
url = url.replace("${H_contract}", vars.H_contract);
@ -43,7 +45,7 @@ export function amountToPretty(amount: AmountJson): string {
* See http://api.taler.net/wallet.html#general
*/
export function canonicalizeBaseUrl(url: string) {
let x = new URI(url);
let x: URI = new URI(url);
if (!x.protocol()) {
x.protocol("https");
}

View File

@ -148,6 +148,53 @@ export interface PreCoin {
}
/**
* Ongoing refresh
*/
export interface RefreshSession {
/**
* Public key that's being melted in this session.
*/
meltCoinPub: string;
/**
* How much of the coin's value is melted away
* with this refresh session?
*/
valueWithFee: AmountJson
/**
* Signature to confirm the melting.
*/
confirmSig: string;
/**
* Denominations of the newly requested coins
*/
newDenoms: string[];
/**
* Blinded public keys for the requested coins.
*/
newCoinBlanks: string[][];
/**
* Blinding factors for the new coins.
*/
newCoinBlindingFactors: string[][];
/**
* Private keys for the requested coins.
*/
newCoinPrivs: string[][];
/**
* The transfer keys, kappa of them.
*/
transferPubs: string[];
}
export interface Reserve {
exchange_base_url: string
reserve_priv: string;
@ -165,7 +212,6 @@ export interface CoinPaySig {
f: AmountJson;
}
/**
* Coin as stored in the "coins" data store
* of the wallet database.

View File

@ -84,6 +84,30 @@ interface CoinViewProps {
coin: Coin;
}
interface RefreshDialogProps {
coin: Coin;
}
class RefreshDialog extends ImplicitStateComponent<RefreshDialogProps> {
refreshRequested = this.makeState<boolean>(false);
render(): JSX.Element {
if (!this.refreshRequested()) {
return (
<div style="display:inline;">
<button onClick={() => this.refreshRequested(true)}>refresh</button>
</div>
);
}
return (
<div>
Refresh amount: <input type="text" size={10} />
<button>ok</button>
<button onClick={() => this.refreshRequested(false)}>cancel</button>
</div>
);
}
}
class CoinView extends preact.Component<CoinViewProps, void> {
render() {
let c = this.props.coin;
@ -94,6 +118,7 @@ class CoinView extends preact.Component<CoinViewProps, void> {
<li>Current amount: {prettyAmount(c.currentAmount)}</li>
<li>Denomination: {abbrev(c.denomPub, 20)}</li>
<li>Suspended: {(c.suspended || false).toString()}</li>
<li><RefreshDialog coin={c} /></li>
</ul>
</div>
);