-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Tx.ts
294 lines (264 loc) · 9.28 KB
/
Tx.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
import { CredentialType, PrivateKey, PubKeyHash, StakeCredentials } from "../credentials";
import { Hash28, Hash32, Signature } from "../hashes";
import { VKeyWitness, VKey, ITxWitnessSet, TxWitnessSet, isITxWitnessSet } from "./TxWitnessSet";
import { CertificateType, PoolParams } from "../ledger";
import { ToCbor, CborString, Cbor, CborObj, CborArray, CborSimple, CanBeCborString, forceCborString } from "@harmoniclabs/cbor";
import { signEd25519 } from "@harmoniclabs/crypto";
import { defineReadOnlyProperty, definePropertyIfNotPresent } from "@harmoniclabs/obj-utils";
import { InvalidCborFormatError } from "../utils/InvalidCborFormatError";
import { ToJson } from "../utils/ToJson";
import { assert } from "../utils/assert";
import { AuxiliaryData } from "./AuxiliaryData";
import { ITxBody, TxBody, isITxBody } from "./body";
export interface ITx {
body: ITxBody
witnesses: ITxWitnessSet
isScriptValid?: boolean
auxiliaryData?: AuxiliaryData | null
}
export interface Cip30LikeSignTx {
/**
*
* @param {string} txCbor receives the current transaction (`this`) cbor
* @param {boolean} partial (standard parameter) wheather to throw or not if the wallet can not sign the entire transaction (`true` always passed)
* @returns {string} the cbor of the `TxWitnessSet` (!!! NOT the cbor of the signe transaction !!!)
*/
signTx: ( txCbor: string, partial?: boolean ) => ( string | Promise<string> )
}
export class Tx
implements ITx, ToCbor, ToJson
{
readonly body!: TxBody
readonly witnesses!: TxWitnessSet
readonly isScriptValid!: boolean
readonly auxiliaryData?: AuxiliaryData | null
/**
* checks that the signer is needed
* if true adds the witness
* otherwise nothing happens (the signature is not added)
*
* one might prefer to use this method instead of `signWith`
* when signature is provided by a third party (example CIP30 wallet)
**/
readonly addVKeyWitness!: ( vkeyWit: VKeyWitness ) => void
/**
* checks that the signer is needed
* if true signs the transaction with the specified key
* otherwise nothing happens (the signature is not added)
**/
readonly signWith!: ( signer: PrivateKey ) => void
/**
* signs the transaction using any browser wallet
* that follows the [CIP-0030 standard]
* (https://github.com/cardano-foundation/CIPs/tree/master/CIP-0030#apisigntxtx-cbortransaction-partialsign-bool--false-promisecbortransaction_witness_set)
**/
readonly signWithCip30Wallet!: ( cip30wallet: Cip30LikeSignTx ) => Promise<void>
/**
* @returns {boolean}
* `true` if all the signers needed
* have signed the transaction; `false` otherwise
*
* signers needed are:
* - required to spend an utxo
* - required by certificate
* - required by withdrawals
* - additional spefified in the `requiredSigners` field
*/
readonly isComplete!: boolean
/**
* getter
*/
readonly hash!: Hash32;
constructor(tx: ITx)
{
const {
body,
witnesses,
isScriptValid,
auxiliaryData
} = tx;
assert(
body instanceof TxBody || isITxBody( body ),
"invalid transaction body; must be instance of 'TxBody'"
);
assert(
isITxWitnessSet( witnesses ),
"invalid wintesses; must be instance of 'TxWitnessSet'"
);
assert(
isScriptValid === undefined || typeof isScriptValid === "boolean",
"'isScriptValid' ('Tx' third paramter) must be a boolean"
);
assert(
auxiliaryData === undefined ||
auxiliaryData === null ||
auxiliaryData instanceof AuxiliaryData,
"invalid transaction auxiliray data; must be instance of 'AuxiliaryData'"
);
defineReadOnlyProperty(
this,
"body",
new TxBody( body )
);
defineReadOnlyProperty(
this,
"witnesses",
new TxWitnessSet( witnesses, getAllRequiredSigners( this.body ) )
);
defineReadOnlyProperty(
this,
"isScriptValid",
isScriptValid === undefined ? true : isScriptValid
);
defineReadOnlyProperty(
this,
"auxiliaryData",
auxiliaryData
);
definePropertyIfNotPresent(
this, "hash",
{
// needs to be a getter because `this.body.hash` is a getter
get: (): Hash32 => this.body.hash,
set: () => {},
enumerable: true,
configurable: false
}
);
//*
defineReadOnlyProperty(
this, "addVKeyWitness",
( vkeyWit: VKeyWitness ) => this.witnesses.addVKeyWitness( vkeyWit )
);
defineReadOnlyProperty(
this, "signWith",
( signer: PrivateKey ): void => {
const [ derivedPubKey, signature ] = signEd25519( this.body.hash.toBuffer(), signer.toBuffer() );
this.addVKeyWitness(
new VKeyWitness(
new VKey( derivedPubKey ),
new Signature( signature )
)
);
}
);
defineReadOnlyProperty(
this, "signWithCip30Wallet",
async ( cip30: Cip30LikeSignTx ): Promise<void> => {
const wits = TxWitnessSet.fromCbor(
await cip30.signTx(
// signTx expects the entire transaction by standard (not only the body ¯\_(ツ)_/¯)
this.toCbor().toString(),
true
)
);
for( const wit of wits.vkeyWitnesses! )
{
this.addVKeyWitness( wit );
}
}
);
Object.defineProperty(
this, "isComplete",
{
// calls the `TxWitnessSet` getter
get: () => this.witnesses.isComplete,
set: () => {},
configurable: false,
enumerable: true
}
);
//*/
}
toCbor(): CborString
{
return Cbor.encode( this.toCborObj() );
}
toCborObj(): CborObj
{
return new CborArray([
this.body.toCborObj(),
this.witnesses.toCborObj(),
new CborSimple( this.isScriptValid ),
this.auxiliaryData === undefined || this.auxiliaryData === null ?
new CborSimple( null ) :
this.auxiliaryData.toCborObj()
])
}
static fromCbor( cStr: CanBeCborString ): Tx
{
return Tx.fromCborObj( Cbor.parse( forceCborString( cStr ) ) );
}
static fromCborObj( cObj: CborObj ): Tx
{
if( !(cObj instanceof CborArray) )
throw new InvalidCborFormatError("Tx");
const [ _body, _wits, _isValid, _aux ] = cObj.array;
if(!(
_isValid instanceof CborSimple &&
typeof (_isValid.simple) === "boolean"
))
throw new InvalidCborFormatError("Tx","isScriptValid is not a boolean")
const noAuxiliaryData = _aux instanceof CborSimple && (_aux.simple === null || _aux.simple === undefined);
return new Tx({
body: TxBody.fromCborObj( _body ),
witnesses: TxWitnessSet.fromCborObj( _wits ),
isScriptValid: _isValid.simple,
auxiliaryData: noAuxiliaryData ? undefined : AuxiliaryData.fromCborObj( _aux )
})
}
toJson()
{
return {
body: this.body.toJson(),
witnesses: this.witnesses.toJson(),
isScriptValid: this.isScriptValid,
auxiliaryData: this.auxiliaryData?.toJson()
}
}
}
/**
* signers needed are:
* - required to spend an utxo
* - required by certificate
* - required by withdrawals
* - additional specified in the `requiredSigners` field
*/
export function getAllRequiredSigners( body: Readonly<TxBody> ): Hash28[]
{
return (
// required for spending pubKey utxo
body.inputs.reduce(
( acc, _in ) => {
const { type, hash } = _in.resolved.address.paymentCreds;
if( type === CredentialType.KeyHash ) acc.push( new PubKeyHash( hash ) );
return acc;
},
[] as Hash28[]
)
// required to sign certificate
.concat(
body.certs?.reduce(
(acc, cert) => acc.concat( cert.getRequiredSigners() ),
[] as Hash28[]
) ?? []
)
// requred for withdrawal
.concat(
body.withdrawals?.map
.map( ({ rewardAccount }) => rewardAccount.credentials.clone() )
?? []
)
// requred signers explicitly specified by the tx
.concat(
...body.requiredSigners
?.map( sig => sig.clone() ) ?? []
)
// remove duplicates
).filter( ( elem, i, thisArr ) => thisArr.indexOf( elem ) === i );
}
export function getNSignersNeeded( body: Readonly<TxBody> ): number
{
const n = getAllRequiredSigners( body ).length
return n === 0 ? 1 : n;
}