-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Address.ts
344 lines (302 loc) · 9.49 KB
/
Address.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
import { ToCbor, CborObj, CborBytes, CborString, Cbor, CanBeCborString, forceCborString } from "@harmoniclabs/cbor";
import { byte, encodeBech32, decodeBech32 } from "@harmoniclabs/crypto";
import { ToData, Data, DataConstr } from "@harmoniclabs/plutus-data";
import { Credential, StakeCredentials, StakeCredentialsType, CredentialType } from "../credentials";
import { Hash28 } from "../hashes";
import { forceBigUInt } from "../utils/ints";
import { NetworkT } from "./Network";
import { defineReadOnlyProperty } from "@harmoniclabs/obj-utils";
import { assert } from "../utils/assert";
import { nothingData, justData } from "../utils/maybeData";
import UPLCFlatUtils from "../utils/UPLCFlatUtils";
import { fromHex, toHex } from "@harmoniclabs/uint8array-utils";
export type AddressStr = `${"addr1"|"addr_test1"}${string}`;
export function isAddressStr( stuff: any ): stuff is AddressStr
{
if( typeof stuff !== "string" ) return false;
try {
Address.fromString( stuff );
return true;
} catch {
return false;
}
}
export type AddressType
= "base"
| "pointer"
| "enterprise"
| "bootstrap"
| "unknown"
/**
* shelley specification in cardano-ledger; page 113
*/
export class Address
implements ToData, ToCbor
{
readonly network!: NetworkT
readonly paymentCreds!: Credential
readonly stakeCreds?: StakeCredentials
readonly type!: AddressType;
static mainnet(
paymentCreds: Credential,
stakeCreds?: StakeCredentials,
type?: AddressType
): Address
{
return new Address(
"mainnet",
paymentCreds,
stakeCreds,
type
);
}
static testnet(
paymentCreds: Credential,
stakeCreds?: StakeCredentials,
type?: AddressType
): Address
{
return new Address(
"testnet",
paymentCreds,
stakeCreds,
type
);
}
constructor(
network: NetworkT,
paymentCreds: Credential,
stakeCreds?: StakeCredentials,
type?: AddressType
)
{
type = type === undefined ?
(stakeCreds === undefined ? "enterprise" : "base")
: type;
assert(
type === "base" ||
type === "enterprise" ||
type === "bootstrap" ||
type === "pointer",
"invalid address type"
);
defineReadOnlyProperty(
this, "type", type
);
assert(
network === "mainnet" || network === "testnet",
"invalid network"
);
defineReadOnlyProperty(
this, "network", network
);
assert(
paymentCreds instanceof Credential,
"invalid payment credentials"
);
defineReadOnlyProperty(
this, "paymentCreds", paymentCreds.clone()
);
assert(
stakeCreds === undefined || stakeCreds instanceof StakeCredentials,
"invalid stake credentials"
);
defineReadOnlyProperty(
this, "stakeCreds", stakeCreds?.clone()
);
}
clone(): Address
{
return new Address(
this.network,
this.paymentCreds, // cloned in constructor
this.stakeCreds, // cloned in constructor
this.type
);
}
static get fake(): Address
{
return new Address(
"mainnet",
Credential.fake
);
}
toData(): Data
{
return new DataConstr(
0, // export has only 1 constructor,
[
this.paymentCreds.toData(),
this.stakeCreds === undefined ?
nothingData() :
justData( this.stakeCreds.toData() )
]
)
}
toBytes(): byte[]
{
return [(
// header byte
// second nubble = network
( this.network === "mainnet" ? 0b0000_0001 : 0b0000_0000 ) |
// first nibble infos
(
this.type === "base" ? 0b0000_0000 :
this.type === "pointer" ? 0b0100_0000 :
this.type === "enterprise" ? 0b0110_0000 :
0b1000 // bootstrap
) |
( this.stakeCreds?.type === "script" ? 0b10_0000 : 0b00_0000 ) |
( this.paymentCreds.type === CredentialType.Script ? 0b01_0000 : 0b00_0000 )
) as byte]
.concat(
Array.from( this.paymentCreds.hash.toBuffer() ) as byte[]
)
.concat(
this.stakeCreds === (void 0) ? [] : // add nothing
Array.isArray( this.stakeCreds.hash ) ? // pointer
this.stakeCreds.hash
.reduce( ( acc, n ) =>
acc.concat(
Array.from(
UPLCFlatUtils.encodeBigIntAsVariableLengthBitStream(
forceBigUInt( n )
).toBuffer().buffer
) as byte[]
),
[] as byte[]
) :
// hash (script or key)
Array.from( this.stakeCreds?.hash.toBuffer() ?? [] ) as byte[]
);
}
static fromBytes( bs: byte[] | string ): Address
{
bs = typeof bs === "string" ? Array.from(fromHex( bs ))as byte[] : bs;
const [ header, ...payload ] = bs;
const addrType = (header & 0b1111_0000) >> 4;
const network: NetworkT = ( (header & 0b0000_1111) ) === 1 ? "mainnet" : "testnet" ;
const type: AddressType =
addrType <= 0b0011 ? "base" :
addrType <= 0b0101 ? "pointer" :
addrType <= 0b0111 ? "enterprise" :
addrType === 0b1000 ? "bootstrap" :
// addrType === 0b1110 || addrType === 0b1111 ? "stake" :
"unknown";
let payment: byte[];
let stake: byte[];
const paymentType: CredentialType = (addrType & 0b0001) === 1 ? CredentialType.Script: CredentialType.KeyHash;
const stakeType: StakeCredentialsType = (addrType & 0b0010) === 1 ? "script": "stakeKey";
switch( type )
{
case "base":
if( payload.length !== (28 * 2) )
throw new Error(
"address' header specifies a base adress but the payload is incorrect"
);
payment = payload.slice( 0, 28 ),
stake = payload.slice( 28 );
break;
case "bootstrap":
case "enterprise":
case "pointer":
if( payload.length < 28 )
{
console.log( toHex( new Uint8Array( payload ) ) )
throw new Error(
"address' payload is incorrect; payload.length: " + payload.length.toString()
);
}
payment = payload.slice(0,28),
stake = []; // ignore pointer; might change in future version
break;
default:
throw new Error("unknown addres type; can't extract payload")
}
if( payment.length !== 28 )
{
throw new Error(
"missing payment credentials"
)
}
return new Address(
network,
new Credential(
paymentType,
new Hash28( new Uint8Array( payment ) )
),
stake.length === 28 ?
new StakeCredentials(
stakeType,
new Hash28( new Uint8Array( stake ) )
):
undefined,
type
);
};
toBuffer(): Uint8Array
{
return new Uint8Array( this.toBytes() )
}
static fromBuffer( buff: Uint8Array | string ): Address
{
return Address.fromBytes(
typeof buff === "string" ?
buff :
Array.from( buff ) as byte[]
)
}
toCborObj(): CborObj
{
return new CborBytes( this.toBuffer() );
}
static fromCborObj( buff: CborObj ): Address
{
if(!( buff instanceof CborBytes))
throw new Error(`Invalid CBOR format for "Address"`);
return Address.fromBuffer( buff.buffer )
}
toCbor(): CborString
{
return Cbor.encode( this.toCborObj() );
}
static fromCbor( cbor: CanBeCborString ): Address
{
return Address.fromCborObj( Cbor.parse( forceCborString( cbor ) ) );
}
toString(): AddressStr
{
return encodeBech32(
this.network === "mainnet" ? "addr" : "addr_test",
this.toBytes()
) as AddressStr;
}
static fromString( addr: string ): Address
{
const [ hrp, bytes ] = decodeBech32( addr );
let hrpNetwork: NetworkT;
switch( hrp )
{
case "addr_test":
hrpNetwork = "testnet";
break;
case "addr":
hrpNetwork = "mainnet";
break;
default:
throw new Error(
"string passed is not a Cardano address"
);
}
const _addr = Address.fromBytes( bytes );
if( hrpNetwork !== _addr.network )
throw new Error(
"ill formed address; human readable part netwok missmatches header byte network"
);
return _addr;
}
toJson()
{
return this.toString();
}
}