-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathcanton.ts
More file actions
249 lines (221 loc) · 7.66 KB
/
canton.ts
File metadata and controls
249 lines (221 loc) · 7.66 KB
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
import {
AuditDecryptedKeyParams,
BaseCoin,
BitGoBase,
KeyPair,
MPCAlgorithm,
MultisigType,
multisigTypes,
ParsedTransaction,
ParseTransactionOptions,
SignedTransaction,
SignTransactionOptions,
TransactionType,
VerifyTransactionOptions,
TransactionExplanation as BaseTransactionExplanation,
BaseTransaction,
PopulatedIntent,
PrebuildTransactionWithIntentOptions,
TssVerifyAddressOptions,
InvalidAddressError,
extractCommonKeychain,
EDDSAMethods,
TokenEnablementConfig,
} from '@bitgo/sdk-core';
import { auditEddsaPrivateKey } from '@bitgo/sdk-lib-mpc';
import { BaseCoin as StaticsBaseCoin, coins } from '@bitgo/statics';
import { TransactionBuilderFactory } from './lib';
import { KeyPair as CantonKeyPair } from './lib/keyPair';
import utils from './lib/utils';
export interface TransactionExplanation extends BaseTransactionExplanation {
type: TransactionType;
}
export interface ExplainTransactionOptions {
txHex: string;
}
export class Canton extends BaseCoin {
protected readonly _staticsCoin: Readonly<StaticsBaseCoin>;
protected constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
super(bitgo);
if (!staticsCoin) {
throw new Error('missing required constructor parameter staticsCoin');
}
this._staticsCoin = staticsCoin;
}
static createInstance(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>): BaseCoin {
return new Canton(bitgo, staticsCoin);
}
private getBuilder(): TransactionBuilderFactory {
return new TransactionBuilderFactory(coins.get(this.getChain()));
}
/** @inheritDoc */
public getBaseFactor(): number {
return 1e10;
}
/** @inheritDoc */
public getChain(): string {
return 'canton';
}
/** @inheritDoc */
public getFamily(): string {
return 'canton';
}
/** @inheritDoc */
public getFullName(): string {
return 'Canton';
}
/** @inheritDoc */
supportsTss(): boolean {
return true;
}
/** inherited doc */
getDefaultMultisigType(): MultisigType {
return multisigTypes.tss;
}
/** inherited doc */
requiresWalletInitializationTransaction(): boolean {
return true;
}
getMPCAlgorithm(): MPCAlgorithm {
return 'eddsa';
}
/** @inheritDoc */
async verifyTransaction(params: VerifyTransactionOptions): Promise<boolean> {
const coinConfig = coins.get(this.getChain());
const { txPrebuild: txPrebuild, txParams } = params;
const rawTx = txPrebuild.txHex;
if (!rawTx) {
throw new Error('missing required tx prebuild property txHex');
}
const txBuilder = new TransactionBuilderFactory(coinConfig).from(rawTx);
const transaction = txBuilder.transaction;
const explainedTx = transaction.explainTransaction();
switch (transaction.type) {
case TransactionType.WalletInitialization:
case TransactionType.TransferAccept:
case TransactionType.TransferReject:
case TransactionType.TransferAcknowledge:
case TransactionType.OneStepPreApproval:
case TransactionType.TransferOfferWithdrawn:
// There is no input for these type of transactions, so always return true.
return true;
case TransactionType.Send:
if (txParams.recipients !== undefined) {
const filteredRecipients = txParams.recipients?.map((recipient) => {
const { address, amount, tokenName } = recipient;
const [addressPart, memoId] = address.split('?memoId=');
return {
address: addressPart,
amount,
...(memoId && { memo: memoId }),
...(tokenName && { tokenName }),
};
});
const filteredOutputs = explainedTx.outputs?.map((output) => {
const { address, amount, tokenName, memo } = output;
return {
address,
amount,
...(memo && { memo }),
...(tokenName && { tokenName }),
};
});
if (JSON.stringify(filteredRecipients) !== JSON.stringify(filteredOutputs)) {
throw new Error('Tx outputs do not match with expected txParams recipients');
}
}
return true;
default: {
throw new Error(`unknown transaction type, ${transaction.type}`);
}
}
}
/** @inheritDoc */
async isWalletAddress(params: TssVerifyAddressOptions): Promise<boolean> {
// TODO: refactor this and use the `verifyEddsaMemoBasedWalletAddress` once published from sdk-core
// https://bitgoinc.atlassian.net/browse/COIN-6347
const { keychains, address: newAddress, index } = params;
const [addressPart, memoId] = newAddress.split('?memoId=');
if (!this.isValidAddress(addressPart)) {
throw new InvalidAddressError(`invalid address: ${newAddress}`);
}
if (memoId && memoId !== `${index}`) {
throw new InvalidAddressError(`invalid memoId index: ${memoId}`);
}
const commonKeychain = extractCommonKeychain(keychains);
const MPC = await EDDSAMethods.getInitializedMpcInstance();
const derivationPath = 'm/0';
const derivedPublicKey = MPC.deriveUnhardened(commonKeychain, derivationPath).slice(0, 64);
const publicKeyBase64 = Buffer.from(derivedPublicKey, 'hex').toString('base64');
const rootAddressFingerprint = utils.getAddressFromPublicKey(publicKeyBase64);
const rootAddress = `${rootAddressFingerprint.slice(0, 5)}::${rootAddressFingerprint}`;
return addressPart === rootAddress;
}
/** @inheritDoc */
parseTransaction(params: ParseTransactionOptions): Promise<ParsedTransaction> {
throw new Error('Method not implemented.');
}
/** @inheritDoc */
generateKeyPair(seed?: Buffer): KeyPair {
const keyPair = seed ? new CantonKeyPair({ seed }) : new CantonKeyPair();
const keys = keyPair.getKeys();
if (!keys.prv) {
throw new Error('Missing prv in key generation.');
}
return {
pub: keys.pub,
prv: keys.prv,
};
}
/** @inheritDoc */
explainTransaction(params: ExplainTransactionOptions): Promise<TransactionExplanation> {
const factory = this.getBuilder();
let rebuiltTransaction: BaseTransaction;
const txRaw = params.txHex;
try {
const txBuilder = factory.from(txRaw);
rebuiltTransaction = txBuilder.transaction;
} catch (e) {
throw new Error('Invalid transaction');
}
return rebuiltTransaction.explainTransaction();
}
/** @inheritDoc */
isValidPub(pub: string): boolean {
return utils.isValidPublicKey(pub);
}
/** @inheritDoc */
isValidAddress(address: string): boolean {
// canton addresses are of the form, partyHint::fingerprint
// where partyHint is of length 5 and fingerprint is 68 characters long
return utils.isValidAddress(address);
}
/** @inheritDoc */
getTokenEnablementConfig(): TokenEnablementConfig {
return {
requiresTokenEnablement: true,
supportsMultipleTokenEnablements: false,
};
}
getAddressFromPublicKey(publicKeyHex: string): string {
const publicKeyBase64 = Buffer.from(publicKeyHex, 'hex').toString('base64');
return utils.getAddressFromPublicKey(publicKeyBase64);
}
/** @inheritDoc */
signTransaction(params: SignTransactionOptions): Promise<SignedTransaction> {
throw new Error('Method not implemented.');
}
/** @inheritDoc */
auditDecryptedKey({ multiSigType, prv, publicKey }: AuditDecryptedKeyParams): void {
if (multiSigType !== multisigTypes.tss) {
throw new Error('Unsupported multiSigType');
}
auditEddsaPrivateKey(prv, publicKey ?? '');
}
/** @inheritDoc */
setCoinSpecificFieldsInIntent(intent: PopulatedIntent, params: PrebuildTransactionWithIntentOptions): void {
if (params.txRequestId) {
intent.txRequestId = params.txRequestId;
}
}
}