-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathutxo.ts
More file actions
798 lines (771 loc) · 24.5 KB
/
utxo.ts
File metadata and controls
798 lines (771 loc) · 24.5 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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
import { H160, H256, U64 } from "codechain-sdk/lib/core/classes";
import * as _ from "lodash";
import * as Sequelize from "sequelize";
import sequelize = require("sequelize");
import models from "..";
import * as Exception from "../../exception";
import { utxoPagination } from "../../routers/pagination";
import { AggsUTXOAttribute } from "../aggsUTXO";
import { AssetSchemeAttribute } from "../assetscheme";
import { TransactionInstance } from "../transaction";
import { AssetTransferOutput } from "../transferAsset";
import { UTXOAttribute, UTXOInstance } from "../utxo";
import * as AggsUTXOModel from "./aggsUTXO";
import * as AssetSchemeModel from "./assetscheme";
import * as BlockModel from "./block";
import { getSuccessfulByTracker } from "./transaction";
import { getOwner } from "./utils/address";
import { strip0xPrefix } from "./utils/format";
export async function createUTXO(
address: string,
utxo: {
assetType: H160;
shardId: number;
lockScriptHash: H160;
parameters: string[];
quantity: U64;
orderHash?: H256 | null;
transactionHash: H256;
transactionTracker: H256;
transactionOutputIndex: number;
transactionIndex: number;
},
blockNumber: number,
options: { transaction?: Sequelize.Transaction } = {}
): Promise<UTXOInstance> {
let utxoInstance;
try {
const assetScheme = await getAssetSheme(utxo.assetType, options);
utxoInstance = await models.UTXO.create(
{
address,
assetType: strip0xPrefix(utxo.assetType.value),
shardId: utxo.shardId,
lockScriptHash: strip0xPrefix(utxo.lockScriptHash.value),
parameters: utxo.parameters.map(p => strip0xPrefix(p)),
quantity: utxo.quantity.value.toString(10),
orderHash: utxo.orderHash
? strip0xPrefix(utxo.orderHash.value)
: null,
transactionHash: strip0xPrefix(utxo.transactionHash.value),
transactionTracker: strip0xPrefix(
utxo.transactionTracker.value
),
transactionOutputIndex: utxo.transactionOutputIndex,
assetScheme,
blockNumber,
transactionIndex: utxo.transactionIndex
},
{
transaction: options.transaction
}
);
} catch (err) {
console.error(err, utxo.assetType.value);
throw Exception.DBError();
}
return utxoInstance;
}
export async function setUsed(
id: string,
blockNumber: number,
usedTransactionHash: H256,
options: { transaction?: Sequelize.Transaction } = {}
) {
try {
return await models.UTXO.update(
{
usedTransactionHash: strip0xPrefix(usedTransactionHash.value),
usedBlockNumber: blockNumber
},
{
where: {
id
},
transaction: options.transaction
}
);
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
export async function setUTXOTransactionIndex(
transactionHash: string,
transactionIndex: number,
options: { transaction?: Sequelize.Transaction } = {}
) {
try {
return await models.UTXO.update(
{
transactionIndex
},
{
where: {
transactionHash
},
transaction: options.transaction
}
);
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
async function getAssetSheme(
assetType: H160,
options: { transaction?: Sequelize.Transaction } = {}
): Promise<AssetSchemeAttribute> {
const assetSchemeInstance = await AssetSchemeModel.getByAssetType(
assetType,
options
);
if (!assetSchemeInstance) {
throw Exception.InvalidTransaction();
}
return assetSchemeInstance.get({
plain: true
});
}
export async function getByAddress(address: string): Promise<UTXOInstance[]> {
try {
return await models.UTXO.findAll({
where: {
address,
usedTransactionHash: null
}
});
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
async function getUTXOQuery(params: {
address?: string | null;
assetType?: H160 | null;
shardId?: number | null;
onlyConfirmed?: boolean | null;
confirmThreshold?: number | null;
firstEvaluatedKey?: number[] | null;
lastEvaluatedKey?: number[] | null;
}) {
const {
address,
shardId,
onlyConfirmed,
confirmThreshold,
assetType,
firstEvaluatedKey,
lastEvaluatedKey
} = params;
const query = [];
if (address) {
query.push({
address
});
}
if (assetType) {
query.push({
assetType: assetType.value
});
}
if (shardId != null) {
query.push({
shardId
});
}
if (onlyConfirmed) {
const latestBlockInst = await BlockModel.getLatestBlock();
const latestBlockNumber = latestBlockInst
? latestBlockInst.get().number
: 0;
query.push({
blockNumber: {
[Sequelize.Op.lte]: latestBlockNumber - confirmThreshold!
}
});
query.push({
[Sequelize.Op.or]: [
{
usedTransactionHash: null
},
{
$usedTransaction$: null
}
]
});
} else {
query.push({
usedTransactionHash: null
});
}
if (firstEvaluatedKey || lastEvaluatedKey) {
query.push(
utxoPagination.where({
firstEvaluatedKey,
lastEvaluatedKey
})
);
}
return query;
}
export async function getUTXO(params: {
address?: string | null;
assetType?: H160 | null;
shardId?: number | null;
itemsPerPage?: number | null;
firstEvaluatedKey?: number[] | null;
lastEvaluatedKey?: number[] | null;
onlyConfirmed?: boolean | null;
confirmThreshold?: number | null;
}) {
const {
address,
assetType,
shardId,
itemsPerPage = 15,
firstEvaluatedKey,
lastEvaluatedKey,
onlyConfirmed = false,
confirmThreshold = 0
} = params;
const query: any = await getUTXOQuery({
address,
assetType,
shardId,
onlyConfirmed,
confirmThreshold,
firstEvaluatedKey,
lastEvaluatedKey
});
let includeArray: any = [
{
as: "usedTransaction",
model: models.Transaction
},
{
as: "assetScheme",
model: models.AssetScheme
}
];
if (onlyConfirmed) {
const latestBlockInst = await BlockModel.getLatestBlock();
const latestBlockNumber = latestBlockInst
? latestBlockInst.get().number
: 0;
includeArray = [
{
as: "usedTransaction",
model: models.Transaction,
required: false,
where: {
blockNumber: {
[Sequelize.Op.lte]:
latestBlockNumber - confirmThreshold!
}
}
},
{
as: "assetScheme",
model: models.AssetScheme
}
];
}
try {
return await models.UTXO.findAll({
where: {
[Sequelize.Op.and]: query
},
order: utxoPagination.orderby({
firstEvaluatedKey,
lastEvaluatedKey
}),
limit: itemsPerPage!,
include: includeArray
});
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
export function createUTXOEvaluatedKey(utxo: UTXOAttribute): string {
return JSON.stringify([
utxo.blockNumber,
utxo.transactionIndex,
utxo.transactionOutputIndex
]);
}
export function createAggsUTXOEvaluatedKey(
aggs: AggsUTXOAttribute,
order: "assetType" | "address"
): string {
return JSON.stringify([
order === "assetType" ? aggs.assetType : aggs.address
]);
}
export async function getAggsUTXO(params: {
order: "assetType" | "address";
address?: string | null;
assetType?: H160 | null;
shardId?: number | null;
itemsPerPage?: number | null;
firstEvaluatedKey?: [number] | null;
lastEvaluatedKey?: [number] | null;
onlyConfirmed?: boolean | null;
confirmThreshold?: number | null;
}) {
const {
order,
address,
assetType,
itemsPerPage = 15,
firstEvaluatedKey,
lastEvaluatedKey
} = params;
try {
if (order === "assetType") {
return await AggsUTXOModel.getByAddress({
address: address!,
assetType,
itemsPerPage,
firstEvaluatedKey,
lastEvaluatedKey
});
} else if (order === "address") {
return await AggsUTXOModel.getByAssetType({
address,
assetType: assetType!,
itemsPerPage,
firstEvaluatedKey,
lastEvaluatedKey
});
} else {
throw new Error("address == aggs == null");
}
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
export async function getCountOfAggsUTXO(params: {
address?: string | null;
assetType?: H160 | null;
shardId?: number | null;
onlyConfirmed?: boolean | null;
confirmThreshold?: number | null;
}) {
const {
address,
assetType,
shardId,
onlyConfirmed = false,
confirmThreshold = 0
} = params;
const query: any = await getUTXOQuery({
address,
assetType,
shardId,
onlyConfirmed,
confirmThreshold
});
let includeArray: any = [];
if (onlyConfirmed) {
const latestBlockInst = await BlockModel.getLatestBlock();
const latestBlockNumber = latestBlockInst
? latestBlockInst.get().number
: 0;
includeArray = [
{
as: "usedTransaction",
model: models.Transaction,
required: false,
where: {
blockNumber: {
[Sequelize.Op.lte]:
latestBlockNumber - confirmThreshold!
}
},
attributes: []
}
];
}
try {
return await models.UTXO.count({
where: {
[Sequelize.Op.and]: query
},
distinct: true,
col: "assetType",
include: includeArray
});
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
export async function getByTxHashIndex(
transactionHash: H256,
outputIndex: number,
options: {
transaction?: Sequelize.Transaction;
} = {}
) {
try {
return await models.UTXO.findOne({
where: {
transactionHash: strip0xPrefix(transactionHash.value),
transactionOutputIndex: outputIndex
},
transaction: options.transaction
});
} catch (err) {
console.error(err);
throw Exception.DBError();
}
}
export async function getSnapshot(params: {
assetType: H256;
blockNumber: number;
lastEvaluatedKey?: number[] | null;
}) {
const { assetType, blockNumber, lastEvaluatedKey } = params;
const transaction = await models.sequelize.transaction({
isolationLevel:
models.Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
deferrable: models.Sequelize.Deferrable.SET_DEFERRED
});
try {
const [
fromBlockNumber,
fromTransactionIndex,
fromTransactionOutputIndex
] = lastEvaluatedKey || [Number.MAX_SAFE_INTEGER, 0, 0];
const itemsPerPage = 100;
const rows = await models.sequelize.query(
`SELECT SUM("UTXO"."quantity") AS "totalAssetQuantity", "UTXO"."address", "UTXO"."assetType",
COUNT("UTXO"."assetType") AS "utxoQuantity"
FROM (SELECT * FROM "UTXOs" WHERE ("blockNumber", "transactionIndex", "transactionOutputIndex")<(:fromBlockNumber, :fromTransactionIndex, :fromTransactionOutputIndex)
AND "assetType"=:assetType
ORDER BY "blockNumber" DESC, "transactionIndex" DESC, "transactionOutputIndex" DESC
LIMIT :itemsPerPage) "UTXO"
WHERE ("UTXO"."usedBlockNumber" > :blockNumber OR "UTXO"."usedBlockNumber" IS NULL)
AND "UTXO"."blockNumber" <= :blockNumber
GROUP BY "UTXO"."address", "UTXO"."assetType"
`,
{
replacements: {
fromBlockNumber,
fromTransactionIndex,
fromTransactionOutputIndex,
blockNumber,
assetType: strip0xPrefix(assetType.toString()),
itemsPerPage
},
raw: true,
transaction,
type: sequelize.QueryTypes.SELECT
}
);
// The SQL query is copied from the query above.
const hasNextPage =
(await models.sequelize.query(
`SELECT COUNT(*) as count
FROM (SELECT id FROM "UTXOs"
WHERE ("blockNumber", "transactionIndex", "transactionOutputIndex")<(:fromBlockNumber, :fromTransactionIndex, :fromTransactionOutputIndex)
AND "assetType"=:assetType
ORDER BY "blockNumber" DESC, "transactionIndex" DESC, "transactionOutputIndex" DESC
LIMIT :itemsPerPage) "UTXO"`,
{
replacements: {
fromBlockNumber,
fromTransactionIndex,
fromTransactionOutputIndex,
assetType: strip0xPrefix(assetType.toString()),
itemsPerPage: itemsPerPage + 1
},
plain: true,
raw: true,
transaction,
type: sequelize.QueryTypes.SELECT
}
)).count === String(itemsPerPage + 1);
// The SQL query is copied from the query above.
const lastRow = await models.sequelize.query(
`SELECT *
FROM (SELECT * FROM "UTXOs" WHERE ("blockNumber", "transactionIndex", "transactionOutputIndex")<(:fromBlockNumber, :fromTransactionIndex, :fromTransactionOutputIndex)
AND "assetType"=:assetType
ORDER BY "blockNumber" DESC, "transactionIndex" DESC, "transactionOutputIndex" DESC
LIMIT :itemsPerPage) "UTXO"
ORDER BY "blockNumber" ASC, "transactionIndex" ASC, "transactionOutputIndex" ASC
LIMIT 1
`,
{
replacements: {
fromBlockNumber,
fromTransactionIndex,
fromTransactionOutputIndex,
assetType: strip0xPrefix(assetType.toString()),
itemsPerPage
},
plain: true,
raw: true,
transaction,
type: sequelize.QueryTypes.SELECT
}
);
const assetScheme = await AssetSchemeModel.getByAssetType(assetType, {
transaction
});
transaction.commit();
return {
data: _.map(rows, (row: any) => {
row.assetScheme =
assetScheme && assetScheme.get({ plain: true });
return row;
}),
hasNextPage,
hasPreviousPage: null,
firstEvaluatedKey: null,
lastEvaluatedKey: lastRow
? JSON.stringify([
lastRow.blockNumber,
lastRow.transactionIndex,
lastRow.transactionOutputIndex
])
: null
};
} catch (err) {
console.error(err);
transaction.rollback();
throw Exception.DBError();
}
}
export async function transferUTXO(
txInst: TransactionInstance,
blockNumber: number,
options: { transaction?: Sequelize.Transaction } = {}
) {
const tx = txInst.get({ plain: true });
const networkId = tx.networkId;
const transactionHash = new H256(tx.hash);
const transactionTracker = new H256(tx.tracker!);
const txType = tx.type;
if (txType === "mintAsset") {
const mintAsset = tx.mintAsset!;
const lockScriptHash = new H160(mintAsset.lockScriptHash);
const parameters = mintAsset.parameters;
const recipient = getOwner(lockScriptHash, parameters, networkId);
const assetType = new H160(mintAsset.assetType);
const shardId = mintAsset.shardId;
const quantity = new U64(mintAsset.supply);
const transactionOutputIndex = 0;
const transactionIndex = tx.transactionIndex!;
return await createUTXO(
recipient,
{
assetType,
shardId,
lockScriptHash,
parameters,
quantity,
transactionHash,
transactionTracker,
transactionOutputIndex,
transactionIndex
},
blockNumber,
options
);
}
if (txType === "transferAsset") {
const transferAsset = tx.transferAsset!;
const { outputs, orders } = transferAsset;
await Promise.all(
outputs!.map(async (output: AssetTransferOutput) => {
const recipient = getOwner(
new H160(output.lockScriptHash),
output.parameters,
networkId
);
const assetType = new H160(output.assetType);
const shardId = output.shardId;
const lockScriptHash = new H160(output.lockScriptHash);
const parameters = output.parameters;
const quantity = new U64(output.quantity);
const orderOnTransfer = orders.find(
o =>
o.outputFromIndices.includes(output.index) ||
o.outputOwnedFeeIndices.includes(output.index) ||
o.outputToIndices.includes(output.index)
);
const order = orderOnTransfer && orderOnTransfer.order;
const orderHash = order && new H256(order.orderHash);
const transactionIndex = tx.transactionIndex!;
return createUTXO(
recipient,
{
assetType,
shardId,
lockScriptHash,
parameters,
quantity,
orderHash,
transactionHash,
transactionTracker,
transactionOutputIndex: output.index,
transactionIndex
},
blockNumber,
options
);
})
);
const { inputs } = await transferAsset;
if (inputs) {
await Promise.all(
inputs.map(async input => {
const prevTracker = input.prevOut.tracker;
const prevTransaction = await getSuccessfulByTracker(
new H256(prevTracker),
options
);
if (!prevTransaction) {
throw Exception.InvalidUTXO();
}
const utxoInst = await getByTxHashIndex(
new H256(prevTransaction.get("hash")),
input.prevOut.index,
options
);
if (!utxoInst) {
throw Exception.InvalidUTXO();
}
return await setUsed(
utxoInst.get("id"),
blockNumber,
transactionHash,
options
);
})
);
}
const { burns } = await transferAsset;
if (burns) {
await Promise.all(
burns.map(async burn => {
const prevTracker = burn.prevOut.tracker;
const prevTransaction = await getSuccessfulByTracker(
new H256(prevTracker),
options
);
if (!prevTransaction) {
throw Exception.InvalidUTXO();
}
const utxoInst = await getByTxHashIndex(
new H256(prevTransaction.get("hash")),
burn.prevOut.index,
options
);
if (!utxoInst) {
throw Exception.InvalidUTXO();
}
return setUsed(
utxoInst.get("id"),
blockNumber,
transactionHash,
options
);
})
);
}
return;
}
if (txType === "increaseAssetSupply") {
const incAssetSupply = tx.increaseAssetSupply!;
const assetType = new H160(incAssetSupply.assetType);
const { shardId, parameters } = incAssetSupply;
const lockScriptHash = new H160(incAssetSupply.lockScriptHash);
const quantity = new U64(incAssetSupply.supply);
const transactionOutputIndex = 0;
const transactionIndex = tx.transactionIndex!;
const recipient = getOwner(
new H160(incAssetSupply.lockScriptHash),
incAssetSupply.parameters,
networkId
);
return createUTXO(
recipient,
{
assetType,
shardId,
lockScriptHash,
parameters,
quantity,
transactionHash,
transactionTracker,
transactionOutputIndex,
transactionIndex
},
blockNumber,
options
);
}
if (txType === "wrapCCC") {
const wrapCCC = tx.wrapCCC!;
const recipient = getOwner(
new H160(wrapCCC.lockScriptHash),
wrapCCC.parameters,
networkId
);
const assetType = H160.zero();
const shardId = wrapCCC.shardId;
const lockScriptHash = new H160(wrapCCC.lockScriptHash);
const parameters = wrapCCC.parameters;
const quantity = new U64(wrapCCC.quantity);
const transactionOutputIndex = 0;
const transactionIndex = tx.transactionIndex!;
return createUTXO(
recipient,
{
assetType,
shardId,
lockScriptHash,
parameters,
quantity,
transactionHash,
transactionTracker,
transactionOutputIndex,
transactionIndex
},
blockNumber,
options
);
}
if (txType === "unwrapCCC") {
const {
burn: { prevOut }
} = await tx.unwrapCCC!;
const prevTracker = prevOut.tracker;
const prevTransaction = await getSuccessfulByTracker(
new H256(prevTracker),
options
);
if (!prevTransaction) {
throw Exception.InvalidUTXO();
}
const utxoInst = await getByTxHashIndex(
new H256(prevTransaction.get("hash")),
prevOut.index,
options
);
if (!utxoInst) {
throw Exception.InvalidUTXO();
}
await setUsed(
utxoInst.get("id"),
blockNumber,
transactionHash,
options
);
}
}