-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathMultiSigWallet.ts
497 lines (445 loc) · 16.4 KB
/
MultiSigWallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import * as Crypto from '@cardano-sdk/crypto';
import {
AccountKeyDerivationPath,
AddressType,
GroupedAddress,
InMemoryKeyAgent,
KeyRole
} from '@cardano-sdk/key-management';
import {
Cardano,
ChainHistoryProvider,
Reward,
RewardsProvider,
Serialization,
TxSubmitProvider,
UtxoProvider,
coalesceValueQuantities,
nativeScriptPolicyId,
util
} from '@cardano-sdk/core';
import { GreedyTxEvaluator, defaultSelectionConstraints } from '@cardano-sdk/tx-construction';
import { InputSelector, StaticChangeAddressResolver, roundRobinRandomImprove } from '@cardano-sdk/input-selection';
import { MultiSigTx } from './MultiSigTx';
import { Observable, firstValueFrom, interval, map, switchMap } from 'rxjs';
import { WalletNetworkInfoProvider } from '@cardano-sdk/wallet';
const randomHexChar = () => Math.floor(Math.random() * 16).toString(16);
const randomPublicKey = () => Crypto.Ed25519PublicKeyHex(Array.from({ length: 64 }).map(randomHexChar).join(''));
// eslint-disable-next-line max-len
const DUMMY_HEX_BYTES =
'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
const DERIVATION_PATH: AccountKeyDerivationPath = {
index: 0,
role: KeyRole.External
};
export class MultiSigWalletProps {
expectedSigners: Array<Crypto.Ed25519PublicKeyHex> = [];
inMemoryKeyAgent: InMemoryKeyAgent;
utxoProvider: UtxoProvider;
chainHistoryProvider: ChainHistoryProvider;
rewardsProvider: RewardsProvider;
txSubmitProvider: TxSubmitProvider;
networkInfoProvider: WalletNetworkInfoProvider;
networkId: Cardano.NetworkId;
pollingInterval: number;
}
/** Represents a multi-signature wallet for Cardano blockchain. */
export class MultiSigWallet {
#expectedSigners: Array<Crypto.Ed25519PublicKeyHex> = [];
#inMemoryKeyAgent: InMemoryKeyAgent;
#multisigScript: Cardano.NativeScript;
#inputSelector: InputSelector;
#address: GroupedAddress;
#utxoProvider: UtxoProvider;
#chainHistoryProvider: ChainHistoryProvider;
#rewardsProvider: RewardsProvider;
#txSubmitProvider: TxSubmitProvider;
#networkInfoProvider: WalletNetworkInfoProvider;
#pollingInterval: number;
/** Creates a new MultiSigWallet instance with the specified signers and network configuration. */
static async createMultiSigWallet(props: MultiSigWalletProps) {
const script = await MultiSigWallet.#buildScript(props.expectedSigners, props.inMemoryKeyAgent);
const address = await MultiSigWallet.#getAddress(script, props.networkId);
const inputSelector = roundRobinRandomImprove({
changeAddressResolver: new StaticChangeAddressResolver(() => Promise.resolve([address]))
});
return new MultiSigWallet(props, script, address, inputSelector);
}
/** Constructs a new MultiSigWallet. */
constructor(
props: MultiSigWalletProps,
script: Cardano.NativeScript,
address: GroupedAddress,
inputSelector: InputSelector
) {
this.#multisigScript = script;
this.#address = address;
this.#inputSelector = inputSelector;
this.#expectedSigners = props.expectedSigners;
this.#inMemoryKeyAgent = props.inMemoryKeyAgent;
this.#utxoProvider = props.utxoProvider;
this.#chainHistoryProvider = props.chainHistoryProvider;
this.#rewardsProvider = props.rewardsProvider;
this.#txSubmitProvider = props.txSubmitProvider;
this.#networkInfoProvider = props.networkInfoProvider;
this.#pollingInterval = props.pollingInterval;
}
/**
* Retrieves the list of signers' public keys.
*
* @returns {Array<Crypto.Ed25519PublicKeyHex>} An array of signers' public keys.
*/
getSigners(): Array<Crypto.Ed25519PublicKeyHex> {
return this.#expectedSigners;
}
/**
* Retrieves the payment address of the wallet.
*
* @returns {Cardano.PaymentAddress} The payment address.
*/
getPaymentAddress(): Cardano.PaymentAddress {
return this.#address.address;
}
/**
* Retrieves the reward account associated with the wallet.
*
* @returns {Cardano.RewardAccount} The reward account.
*/
getRewardAccount(): Cardano.RewardAccount {
return this.#address.rewardAccount;
}
/**
* Delegates the stake to a specified pool.
*
* @param {Cardano.PoolId} pool - The pool ID to delegate to.
* @returns {Promise<MultiSigTx>} A multi-signature transaction object for the delegation.
*/
async delegate(pool: Cardano.PoolId): Promise<MultiSigTx> {
const certificates: Cardano.Certificate[] = [];
certificates.push(
{
__typename: Cardano.CertificateType.StakeRegistration,
stakeCredential: {
hash: Cardano.RewardAccount.toHash(this.getRewardAccount()) as unknown as Crypto.Hash28ByteBase16,
type: Cardano.CredentialType.ScriptHash
}
},
{
__typename: Cardano.CertificateType.StakeDelegation,
poolId: pool,
stakeCredential: {
hash: Cardano.RewardAccount.toHash(this.getRewardAccount()) as unknown as Crypto.Hash28ByteBase16,
type: Cardano.CredentialType.ScriptHash
}
}
);
const { body, id } = await this.#createTransaction(
// Add dummy output. This is not needed, but probably ok for POC.
new Set<Cardano.TxOut>([
{
address: this.getPaymentAddress(),
value: { coins: 1_000_000n }
}
]),
certificates
);
return new MultiSigTx(
{
body,
id,
witness: {
scripts: [this.#multisigScript],
signatures: new Map<Crypto.Ed25519PublicKeyHex, Crypto.Ed25519SignatureHex>()
}
},
this.#expectedSigners
);
}
/**
* Transfers funds to a specified address.
*
* @param {Cardano.PaymentAddress} address - The address to transfer funds to.
* @param {Cardano.Value} value - The amount to be transferred.
* @returns {Promise<MultiSigTx>} A multi-signature transaction object for the transfer.
*/
async transferFunds(address: Cardano.PaymentAddress, value: Cardano.Value): Promise<MultiSigTx> {
const { body, id } = await this.#createTransaction(
new Set<Cardano.TxOut>([
{
address,
value
}
])
);
return new MultiSigTx(
{
body,
id,
witness: {
scripts: [this.#multisigScript],
signatures: new Map<Crypto.Ed25519PublicKeyHex, Crypto.Ed25519SignatureHex>()
}
},
this.#expectedSigners
);
}
/**
* Signs a multi-signature transaction.
*
* @param {MultiSigTx} multiSigTx - The multi-signature transaction to sign.
* @returns {Promise<MultiSigTx>} The signed multi-signature transaction.
*/
async sign(multiSigTx: MultiSigTx): Promise<MultiSigTx> {
const currentSignatures = multiSigTx.getTransaction().witness.signatures;
const newSignatures = await this.#inMemoryKeyAgent.signTransaction(
{
body: multiSigTx.getTransaction().body,
hash: multiSigTx.getTransaction().id
},
{ knownAddresses: [this.#address], txInKeyPathMap: {} },
{ additionalKeyPaths: [DERIVATION_PATH] }
);
for (const signature of newSignatures.entries()) {
currentSignatures.set(signature[0], signature[1]);
}
multiSigTx.getTransaction().witness.signatures = currentSignatures;
return multiSigTx;
}
/**
* Submits a signed multi-signature transaction to the network.
*
* @param {MultiSigTx} multiSigTx - The signed multi-signature transaction to submit.
* @returns {Promise<Cardano.TransactionId>} The transaction ID of the submitted transaction.
*/
async submit(multiSigTx: MultiSigTx): Promise<Cardano.TransactionId> {
const tx = Serialization.Transaction.fromCore(multiSigTx.getTransaction());
await this.#txSubmitProvider.submitTx({
signedTransaction: tx.toCbor()
});
return tx.getId();
}
/**
* Retrieves the set of unspent transaction outputs (UTXOs) associated with the wallet.
*
* @returns {Observable<Cardano.Utxo[]>} A hot observable with the list of current UTXOs.
*/
getUtxoSet(): Observable<Cardano.Utxo[]> {
return interval(this.#pollingInterval).pipe(
switchMap(
() =>
new Observable<Cardano.Utxo[]>((subscriber) => {
this.#utxoProvider
.utxoByAddresses({ addresses: [this.#address.address] })
.then((utxos) => {
subscriber.next(utxos);
})
.catch((error) => subscriber.error(error));
})
)
);
}
/**
* Calculates and returns the total balance of the wallet.
*
* @returns {Observable<Cardano.Value>} An observable that emits the wallet's balance.
*/
getBalance(): Observable<Cardano.Value> {
return this.getUtxoSet().pipe(map((utxoSet) => coalesceValueQuantities(utxoSet.map((utxo) => utxo[1].value))));
}
/**
* Retrieves and emits the transaction history of the wallet at specified polling intervals.
*
* @returns {Observable<Cardano.HydratedTx[]>} An observable that emits the list of historical transactions.
*/
getTransactionHistory(): Observable<Cardano.HydratedTx[]> {
return interval(this.#pollingInterval).pipe(
switchMap(
() =>
new Observable<Cardano.HydratedTx[]>((subscriber) => {
this.#chainHistoryProvider
.transactionsByAddresses({
addresses: [this.#address.address],
pagination: {
limit: 25, // Gets only the first 25 transaction. This is probably good enough for the POC.
startAt: 0
}
})
.then((paginatedTxs) => {
subscriber.next(paginatedTxs.pageResults);
subscriber.complete();
})
.catch((error) => subscriber.error(error));
})
)
);
}
/**
* Retrieves and emits the rewards history of the wallet's reward account at specified polling intervals.
*
* @returns {Observable<Map<Cardano.RewardAccount, Reward[]>>} An observable that emits the rewards history.
*/
getRewardsHistory(): Observable<Map<Cardano.RewardAccount, Reward[]>> {
return interval(this.#pollingInterval).pipe(
switchMap(
() =>
new Observable<Map<Cardano.RewardAccount, Reward[]>>((subscriber) => {
this.#rewardsProvider
.rewardsHistory({
rewardAccounts: [this.#address.rewardAccount]
})
.then((rewardsHistory) => {
subscriber.next(rewardsHistory);
subscriber.complete();
})
.catch((error) => subscriber.error(error));
})
)
);
}
/**
* Retrieves and emits the current balance of the reward account at specified polling intervals.
*
* @returns {Observable<Cardano.Lovelace>} An observable that emits the balance of the reward account.
*/
getRewardAccountBalance(): Observable<Cardano.Lovelace> {
return interval(this.#pollingInterval).pipe(
switchMap(
() =>
new Observable<Cardano.Lovelace>((subscriber) => {
this.#rewardsProvider
.rewardAccountBalance({
rewardAccount: this.#address.rewardAccount
})
.then((rewardAccountBalance) => {
subscriber.next(rewardAccountBalance);
subscriber.complete();
})
.catch((error) => subscriber.error(error));
})
)
);
}
/**
* Internally used method to build the multi-signature script.
*
* @param {Array<Crypto.Ed25519PublicKeyHex>} expectedSigners - The public keys expected to sign transactions.
* @param {InMemoryKeyAgent} keyAgent - The in-memory key agent.
* @returns {Promise<Cardano.NativeScript>} The constructed native script.
*/
static async #buildScript(expectedSigners: Array<Crypto.Ed25519PublicKeyHex>, keyAgent: InMemoryKeyAgent) {
const signers = [...expectedSigners];
// Sorting guarantees that we will always get the same script if the same keys are used.
signers.sort();
// We are going to use RequireAllOf for this POC to keep it simple, but RequireNOf makes more sense.
const script: Cardano.NativeScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireAllOf,
scripts: []
};
for (const signer of signers) {
script.scripts.push({
__type: Cardano.ScriptType.Native,
keyHash: await keyAgent.bip32Ed25519.getPubKeyHash(signer),
kind: Cardano.NativeScriptKind.RequireSignature
});
}
return script;
}
/**
* Internally used method to derive the wallet's grouped address from the script and network ID.
*
* @param {Cardano.NativeScript} script - The native script for multi-signature.
* @param {Cardano.NetworkId} networkId - The network identifier.
* @returns {Promise<GroupedAddress>} The derived grouped address.
*/
static async #getAddress(script: Cardano.NativeScript, networkId: Cardano.NetworkId): Promise<GroupedAddress> {
const scriptHash = nativeScriptPolicyId(script) as unknown as Crypto.Hash28ByteBase16;
const scriptCredential = {
hash: scriptHash,
type: Cardano.CredentialType.ScriptHash
};
const baseAddress = Cardano.BaseAddress.fromCredentials(
Cardano.NetworkId.Testnet,
scriptCredential,
scriptCredential
);
return {
accountIndex: 0,
address: baseAddress.toAddress().toBech32() as Cardano.PaymentAddress,
index: 0,
networkId,
rewardAccount: Cardano.RewardAddress.fromCredentials(networkId, scriptCredential)
.toAddress()
.toBech32() as Cardano.RewardAccount,
type: AddressType.External
};
}
/**
* Internally used method to create a transaction with the given outputs and certificates.
*
* @param {Set<Cardano.TxOut>?} txOuts - The set of transaction outputs.
* @param {Cardano.Certificate[]?} certificates - The list of certificates to include in the transaction.
* @returns {Promise<{ body: Cardano.TxBody, id: Cardano.TransactionId }>} The transaction body and ID.
*/
async #createTransaction(txOuts?: Set<Cardano.TxOut>, certificates?: Cardano.Certificate[]) {
const [protocolParameters, utxo] = await Promise.all([
this.#networkInfoProvider.protocolParameters(),
firstValueFrom(this.getUtxoSet())
]);
const withdrawals: Cardano.Withdrawal[] = [];
const rewardsBalance = await firstValueFrom(this.getRewardAccountBalance());
if (rewardsBalance > 0) {
withdrawals.push({ quantity: rewardsBalance, stakeAddress: this.getRewardAccount() });
}
const constraints = defaultSelectionConstraints({
buildTx: async (inputSelection) => {
const body: Cardano.TxBody = {
certificates,
fee: inputSelection.fee,
inputs: [...inputSelection.inputs].map(([txIn]) => txIn),
outputs: txOuts ? [...txOuts.values()] : [],
...(withdrawals.length > 0 ? { withdrawals } : {})
};
const signatureMap = new Map();
// TODO: There is a small bug here and the fee is off by a few lovelace, this *2 will offset
// the error in the meantime.
for (let i = 0; i < this.#expectedSigners.length * 2; ++i)
signatureMap.set(randomPublicKey(), DUMMY_HEX_BYTES as Crypto.Ed25519SignatureHex);
return {
body,
id: '' as Cardano.TransactionId,
witness: {
scripts: [this.#multisigScript],
signatures: signatureMap
}
};
},
protocolParameters,
redeemersByType: {},
txEvaluator: new GreedyTxEvaluator(() => this.#networkInfoProvider.protocolParameters())
});
const implicitCoin = Cardano.util.computeImplicitCoin(protocolParameters, {
certificates,
withdrawals
});
const { selection: inputSelection } = await this.#inputSelector.select({
constraints,
implicitValue: { coin: implicitCoin },
outputs: txOuts || new Set(),
preSelectedUtxo: new Set(),
utxo: new Set(utxo)
});
const body = {
certificates,
fee: inputSelection.fee,
inputs: [...inputSelection.inputs].map(([txIn]) => txIn),
outputs: txOuts ? [...inputSelection.outputs, ...inputSelection.change] : [],
withdrawals
};
const serializableBody = Serialization.TransactionBody.fromCore(body);
const id = Cardano.TransactionId.fromHexBlob(
util.bytesToHex(Crypto.blake2b(Crypto.blake2b.BYTES).update(util.hexToBytes(serializableBody.toCbor())).digest())
);
return { body, id };
}
}