forked from Colored-Coins/coloredcoinsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coluutils.js
1540 lines (1314 loc) · 58.4 KB
/
coluutils.js
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module.exports = (function () {
var config = require("./config")
var Client = require('node-rest-client').Client
var Q = require("q");
var rpc = require("bitcoin")
var AWS = require("aws-sdk")
var crypto = require('crypto')
var bitcoinjs = require('bitcoinjs-lib')
var bn = require('bignumber.js')
var cc = require('cc-transaction')
var assetIdencoder = require('cc-assetid-encoder')
var _ = require('lodash')
var rsa = require('node-rsa')
var findBestMatchByNeededAssets = require('./modules/findBestMatchByNeededAssets')
var creds = {}
creds.AWSAKI = process.env.AWSAKI
creds.AWSSSK = process.env.AWSSSK
var CC_TX_VERSION = 0x02
var client = new Client()
var rpcclient = new rpc.Client(config.bitcoind)
function coluutils() {
//client.registerMethod("getaddressutxos", config.blockexplorer.url + "/api/getaddressutxos?address=${address}", "GET")
client.registerMethod("getaddressutxos", config.blockexplorer.url + "/api/getaddressesutxos", "POST")
client.registerMethod("getassetholders", config.blockexplorer.url + "/api/getassetholders?assetId=${assetid}&confirmations=${minconf}", "GET")
client.registerMethod("getassetinfo", config.blockexplorer.url + "/api/getassetinfo?assetId=${assetid}&utxo=${utxo}&verbosity=${verbosity}", "GET")
client.registerMethod("gettransaction", config.blockexplorer.url + "/api/gettransaction?txid=${txid}", "GET")
client.registerMethod("getutxo", config.blockexplorer.url + "/api/getutxos", "POST")
client.registerMethod("broadcasttx", config.blockexplorer.url + "/api/transmit", "POST")
// client.registerMethod("getutxo", config.blockexplorer.url + "/api/getutxo?txid=${txid}&index=${index}", "GET")
client.registerMethod("preparsetx", config.blockexplorer.url + "/api/parsetx?txid=${txid}", "POST")
client.registerMethod("upload", config.torrentServer.url + "/addMetadata?token=${token}", "POST")
client.registerMethod("seed", config.torrentServer.url + "/shareMetadata?token=${token}&torrentHash=${torrentHash}", "GET")
client.registerMethod("download", config.torrentServer.url + "/getMetadata?token=${token}&torrentHash=${torrentHash}", "GET")
}
coluutils.safeParse = function safeParse (item) {
try {
if ((typeof item === 'string') || (item instanceof Buffer)) {
return JSON.parse(item)
} else {
return item
}
} catch (e) {
return item
}
}
var safeParse = coluutils.safeParse
coluutils.sendRawTransaction = function sendRawTransaction(txHex) {
return callservice('sendrawtransaction',txHex)
}
coluutils.getBlockCount = function getBlockCount() {
return callservice('getblockcount')
}
coluutils.broadcastTxBitcoind = function broadcastTxBitcoind(txHex) {
return callservice('sendrawtransaction', txHex)
}
coluutils.getTransactionListForAddress = function getTransactionListForAddress(address, no_confirmations) {
var deferred = Q.defer()
var confirmations = no_confirmations || 0
callservice('listunspent', confirmations)
.then(function(unspents) {
console.log('got unspents')
var batch = []
unspents.forEach(function(unspent){
batch.push({method: "getrawtransaction", params:[unspent.txid,1]});
})
callwithbatch(batch)
.then(function(transactions){
var useable = unspents.filter(function(unspent, i) {
console.log("checking unspent " + unspent.txid + ":" + unspent.vout)
var keep = true;
if(config.checkFinanaceValidty) {
transactions[i].vout.some(function(vout, x){
if(vout.scriptPubKey &&
vout.scriptPubKey.asm &&
vout.scriptPubKey.asm.indexOf("OP_RETURN") != -1)
{
// if its our rncoding then check the ouput isn't a color
if(!isOkToIssue(vout, unspent.vout)) {
keep = false;
console.log("input removed: " + vout.scriptPubKey.asm )
return true;
}
}
return x == (transactions[i].vout.length -1);
})
} // check validity
unspent.transaction = transactions[i];
console.log(unspent.txid + " keep: " + keep)
return keep;
}) //unsepnts.filter
console.log('resovle get inputs')
console.log(useable)
// console.log(unspents)
deferred.resolve(useable);
})
})
return deferred.promise;
}
function callwithbatch(batch) {
var ret =[];
var deferred = Q.defer();
console.log('batching')
console.log(batch)
rpcclient.cmd(batch, function(err, data, placeholder, done){
console.log('still batching')
if(err) ret.push(err)
else ret.push(data)
if(done)
{
console.log('batching done')
deferred.resolve(ret);
}
})
return deferred.promise;
}
function isOkToIssue(vout, index)
{
var isok = false;
if (vout.scriptPubKey && vout.scriptPubKey.type == 'nulldata') {
console.log('found OP_RETURN')
var hex = get_opreturn_data(vout.scriptPubKey.hex) // remove op_return (0x6a) and data length?
console.log(hex)
if (check_version(hex)) {
console.log('hex: ', hex)
var ccdata = cc.createFromHex(hex).toJson()
ccdata.payments.some(function(payment){
if(payment.output != index)
isok = true;
else
isok = false
return !isok;
})
}
}
return isok;
}
var check_version = function (hex) {
var version = hex.toString('hex').substring(0, 4)
if (version.toLowerCase() == '4343') {
return true
}
return false
}
var get_opreturn_data = function (hex) {
return hex.substring(4)
}
function callservice() {
var deferred = Q.defer();
var args = [].slice.call(arguments);
var command = args[0];
args.shift();
var batch = [{
method: command,
params: args
}];
rpcclient.cmd(batch, function(err){
if (err) {
console.log(err);
deferred.reject(new Error("Bitcoind: Status code was " + err));
}
else {
deferred.resolve(arguments[1]);
}
});
return deferred.promise;
}
coluutils.validateIssueTrasaction = function validateIssueTrasaction(data) {
var deferred = Q.defer();
// lets check if this is the first issue
var key = sha1(sha256(data)).toString('hex');
// send key to sevice to check if we already have it
AWS.config.update({ accessKeyId: process.env.AWSAKI,
secretAccessKey: process.env.AWSSSK });
var s3bucket = new metadatOfUtxo({params: {Bucket: 'coloredcoin-assets'}});
s3bucket.headObject({Key: key}, function(error, headobject){
if(error && error.code === "NotFound") {
//all is well
deferred.resolve(data);
}
else {
// are we reissueing
if(data.reissue) {
}
else
deferred.reject(new Error("cant reissue without correct assetId"));
}
});
// check with block explorer that transaction is ok
return deferred.promise;
}
coluutils.createIssueTransaction = function createIssueTransaction(metadata) {
var deferred = Q.defer();
metadata.divisibility = metadata.divisibility || 0
metadata.aggregationPolicy = metadata.aggregationPolicy || 'aggregatable'
tx = new bitcoinjs.Transaction();
// find inputs to cover the issuence
addInputsForIssueTransaction(tx, metadata).
then(function(args){
var txResponse = encodeColorScheme(args);
deferred.resolve({txHex: txResponse.tx.toHex(), assetId: args.assetId || "0", metadata: metadata, multisigOutputs: txResponse.multisigOutputs, coloredOutputIndexes: txResponse.coloredOutputIndexes});
}).
catch(function(err) {
deferred.reject(err);
});
return deferred.promise;
}
coluutils.createSendAssetTansaction = function createSendAssetTansaction(metadata) {
var deferred = Q.defer();
tx = new bitcoinjs.Transaction();
// find inputs to cover the issuence
addInputsForSendTransaction(tx, metadata).
then(validateFees).
then(function(data){
console.log(data.tx)
deferred.resolve(data);
}).
catch(function(err) {
console.log(err)
deferred.reject(err);
});
return deferred.promise;
}
function validateFees(data){
var self = this
var deferred = Q.defer()
data.tx.ins.forEach( function (input) {
console.log('in:' + input.script.buffer.length)
})
data.tx.outs.forEach( function (txOut) {
console.log('out:' + txOut.script.buffer.length)
})
console.log('fee per kb: ' + data.tx.toBuffer().length /1000.0)
deferred.resolve(data)
return deferred.promise;
}
function encodeColorScheme(args) {
var addMultisig = false;
var metadata = args.metadata
var encoder = cc.newTransaction(0x4343, CC_TX_VERSION)
var reedemScripts = []
var coloredOutputIndexes = []
encoder.setLockStatus(!metadata.reissueable)
encoder.setAmount(metadata.amount, metadata.divisibility)
console.log("amount and div " + metadata.amount+" "+ metadata.divisibility)
encoder.setAggregationPolicy(metadata.aggregationPolicy)
console.log('aggregationPolicy = ' + metadata.aggregationPolicy)
if(metadata.metadata || metadata.rules) {
if(config.writemultisig) {
if(!metadata.sha1 || !metadata.sha2) {
console.log("something went wrong with torrent sever")
throw new Error('missing sha1 or sha2 cannot issue, check torrent server')
}
encoder.setHash(metadata.sha1, metadata.sha2)
}
}
//console.log(metadata.transfer)
if(metadata.transfer) {
metadata.transfer.forEach(function(transferobj, i){
console.log("payment " + transferobj.amount + " " + args.tx.outs.length )
encoder.addPayment(0, transferobj.amount, args.tx.outs.length)
// check multisig
if(transferobj.pubKeys && transferobj.m) {
var multisig = generateMultisigAddress(transferobj.pubKeys, transferobj.m)
reedemScripts.push({index: args.tx.outs.length , reedemScript: multisig.reedemScript, address: multisig.address})
args.tx.addOutput(multisig.address, config.mindustvalue)
}
else
args.tx.addOutput(transferobj.address, config.mindustvalue)
})
}
//add op_return
console.log("before encode done")
var buffer = encoder.encode()
console.log("encoding done, buffer: ")
if(buffer.leftover && buffer.leftover.length > 0)
{
encoder.shiftOutputs()
buffer = encoder.encode()
addMultisig = true;
reedemScripts.forEach(function(item) { item.index +=1 })
}
var ret = bitcoinjs.Script.fromChunks(
[
bitcoinjs.opcodes.OP_RETURN,
buffer.codeBuffer
]);
args.tx.addOutput(ret, 0);
// add array of colored ouput indexes
encoder.payments.forEach(function (payment) {
coloredOutputIndexes.push(payment.output)
})
// need to encode hashes in first tx
if(addMultisig) {
if(buffer.leftover && buffer.leftover.length == 1)
addHashesOutput(args.tx, metadata.pubKeyReturnMultisigDust, buffer.leftover[0])
else if(buffer.leftover && buffer.leftover.length == 2)
addHashesOutput(args.tx, metadata.pubKeyReturnMultisigDust, buffer.leftover[1], buffer.leftover[0])
else
throw new Error('have hashes and enough room we offested inputs for nothing')
}
//console.log(args)
// add change
var allOutputValues = _.sumBy(args.tx.outs, function(output) { return output.value; });
console.log('all inputs: ' + args.totalInputs.amount + ' all outputs: ' + allOutputValues);
var lastOutputValue = args.totalInputs.amount - (allOutputValues + metadata.fee)
if(lastOutputValue < config.mindustvalue) {
var totalmisssing = (config.mindustvalue - lastOutputValue) + args.totalInputs.amount.toNumber()
var reply = new Error('not enough satoshi to cover issuence')
reply.json = {error: 'not enough satoshi to cover issuence', missing: config.mindustvalue - lastOutputValue, fee: metadata.fee, total: totalmisssing}
throw reply
}
console.log('adding change output with: ' + lastOutputValue)
console.log('total inputs: ' + args.totalInputs.amount)
console.log('total fee: ' + metadata.fee)
console.log('total output without fee: ' + allOutputValues)
args.tx.addOutput(metadata.issueAddress , lastOutputValue ? lastOutputValue : args.change);
return { tx: args.tx, multisigOutputs: reedemScripts, coloredOutputIndexes: _.uniq(coloredOutputIndexes)}
}
coluutils.getAssetMetadata = function getAssetMetadata(assetId, utxo, verbosity) {
var self = this
var deferred = Q.defer()
getAssetInfo(assetId, utxo, verbosity).
then(function(data){
if(!data.issuanceTxid) {
if(utxo) {
console.log('rejecting request since issuanceTxid is missing for specific utxo')
deferred.reject(new Error('missing issuanceTxid for utxo: ' + utxo))
}
else {
deferred.resolve(data)
}
}
else
{
var txid = utxo.split(':')[0]
var promises = []
promises.push(getTransastion(data.issuanceTxid))
if(data.issuanceTxid !== txid) promises.push(getTransastion(txid))
console.log('requesting issue tx: ' + data.issuanceTxid)
console.log('requesting utxo tx: ' + txid)
Q.all(promises).done(function(values){
var hashes = []
var getHashes = []
var multisignum = 0
values.forEach(function(txbufer, i) {
var tx = safeParse(txbufer)
console.log('tx', tx)
//console.log('values', values)
//console.log('txbufer', txbufer)
console.log(tx.vout[0].scriptPubKey.hex)
if(!i) {
console.log(tx.vin[0])
if(tx.vin[0] && tx.vin[0].previousOutput.addresses[0])
data.issueAddress = tx.vin[0].previousOutput.addresses[0]
}
var script = {}
if(tx.ccdata[0].multiSig && tx.ccdata[0].multiSig.length > 0) {
script = bitcoinjs.Script.fromHex(tx.vout[0].scriptPubKey.hex)
multisignum = script.chunks.length - 3;
console.log('multisignum: ' + multisignum);
}
else if(!tx.ccdata[0].torrentHash) {
console.log('no metadata anywhere for ' + (i ? 'utxo' : 'issue'))
return;
}
var sha1 = tx.ccdata[0].torrentHash || script.chunks[3]
var sha2 = tx.ccdata[0].sha2 || script.chunks[2]
hashes.push({sha1: sha1, sha2: sha2})
console.log('requesting torrent by hash: ' + sha1)
getHashes.push(self.downloadMetadata(sha1))
})
if(getHashes.length == 0) {
deferred.resolve(data)
}
else {
Q.all(getHashes).done(function(metas){
var first = safeParse(metas[0])
var second = metas.length > 1 ? safeParse(metas[1]) : first
data.metadataOfIssuence = first
data.sha2Issue = hashes[0].sha2.toString('hex')
if(metas.length > 1){
data.metadataOfUtxo = second
data.sha2Utxo = hashes[1].sha2.toString('hex')
}
deferred.resolve(data)
}, function(err){
deferred.reject(new Error(err))
})
}
})
}
}).
catch(function(error) {
console.log(error)
deferred.reject(new Error(error))
});
return deferred.promise
}
coluutils.seedMetadata = function seedMetadata(hash) {
var deferred = Q.defer()
var token = config.torrentServer.token
if(!hash) {
console.log('no metadata to seed')
deferred.resolve()
return deferred.promise;
}
var args = {
path: { "token": token,
"torrentHash": hash },
headers:{"Content-Type": "application/json"}
}
client.methods.seed(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("seed:(200) " + data);
//var torretdata = safeParse(data)
deferred.resolve(data);
}
else if(data) {
console.log("seed: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("seed: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('seed: something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
return deferred.promise;
}
coluutils.downloadMetadata = function downloadMetadata(hash) {
var deferred = Q.defer()
var token = config.torrentServer.token
if(!hash) {
console.log('no metadata to seed')
deferred.resolve()
return deferred.promise;
}
var args = {
path: { "token": token,
"torrentHash": hash },
headers:{"Content-Type": "application/json"}
}
client.methods.download(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("download:(200) " + data);
var torretdata = null
try{ torretdata = safeParse(data) } catch(e) {torretdata = data }
deferred.resolve(torretdata);
}
else if(data) {
console.log("download: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error('no response form torrent server'));
}
else {
console.log("download: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('download: something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
return deferred.promise;
}
coluutils.uploadMetadata = function uploadMetadata(metadata)
{
console.log('uploadMetadata')
var deferred = Q.defer()
var token = config.torrentServer.token
console.log(metadata.metadata)
if(!metadata.metadata && !metadata.rules) {
console.log('uploadMetadata: no metadata and no rules')
deferred.resolve(metadata)
return deferred.promise
}
var metafile = {}
if(metadata.metadata) {
var key = tryEncryptData(metadata)
if(key && key.error) {
deferred.reject(new Error("Encryption error " + key.error))
return deferred.promise
}
else if(key && key.privateKey) {
metadata.privateKey = key.privateKey
}
metafile.data = metadata.metadata
}
if(metadata.rules)
metafile.rules = metadata.rules
var args = {
path: { "token": token },
data : {
"metadata": metafile
},
headers:{"Content-Type": "application/json"}
}
client.methods.upload(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("upload:(200) ", data);
var torretdata = safeParse(data)
metadata.sha1 = torretdata.torrentHash
metadata.sha2 = torretdata.sha2
deferred.resolve(metadata);
}
else if(data) {
console.log("rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
return deferred.promise;
}
function tryEncryptData(metadata) {
try {
if(metadata.metadata && metadata.metadata.encryptions && metadata.metadata.userData) {
var oneKey = new rsa({b: 1024})
var returnKey = false
metadata.metadata.encryptions.forEach(function (encSection){
returnKey = returnKey || !encSection.pubKey
var section = metadata.metadata.userData[encSection.key]
if(section) {
var format = encSection.type + '-public-' + encSection.format
var key = encSection.pubKey ? new rsa([encSection.pubKey]) : oneKey
var encrypted = key.encrypt(section, 'base64')
metadata.metadata.userData[encSection.key] = encrypted
console.log(encSection.key + ' encrypted to ' + encrypted )
}
})
return { privateKey: returnKey ? oneKey.exportKey('pkcs8').toString('hex') : '' }
}
}
catch(e) {
console.log('tryEncryptData: exception' + e)
return { error: e }
}
}
function getUnspentArrayByAddressOrUtxo(address, utxo) {
var deferred = Q.defer();
try{
if(utxo) {
console.log('using specific utxo: ' + utxo)
getUtxo(Array.isArray(utxo) ? utxo : [utxo]).
then(function (data) {
if(Array.isArray(data)) {
var reply = []
data.forEach(function (utxolist) {
var utxolistjson = safeParse(utxolist)
if(Array.isArray(utxolistjson))
{
utxolistjson.forEach(function (autxo) { reply.push(autxo) })
}
else
{
reply.push(utxolistjson)
}
})
deferred.resolve(reply)
}
else {
var jsondata = safeParse(data)
deferred.resolve(data)
}
})
}
else {
console.log('using utxo for address: ' + address)
getUnspentsByAddress(Array.isArray(address) ? address : [address]).
then(function (data) {
var utxos = []
var jsondata = data
jsondata.forEach(function (item) {
item.utxos.forEach(function (utxo) {
utxos.push(utxo)
})
})
deferred.resolve(utxos)
})
}
}
catch(e){
deferred.reject(e);
}
return deferred.promise
}
function getUtxo(utxo) {
var deferred = Q.defer();
var args = {
//path: { "txid": txid, "index": index},
data: {
utxos: []
},
headers:{"Content-Type": "application/json"}
}
try{
utxo.forEach(function (utxostring) {
args.data.utxos.push({txid: utxostring.split(':')[0], index: utxostring.split(':')[1]})
})
client.methods.getutxo(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("getUtxo:(200)");
deferred.resolve([data]);
}
else if(data) {
console.log("getUtxo: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("getUtxo: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e) }
return deferred.promise;
}
function getTransastion(txid) {
var deferred = Q.defer();
var args = {
path: { "txid": txid },
headers:{"Content-Type": "application/json"}
}
try{
client.methods.gettransaction(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("getTransastion:(200)");
deferred.resolve(data);
}
else if(data) {
console.log("getTransastion: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("getTransastion: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e) }
return deferred.promise;
}
coluutils.broadcastTx = function broadcastTx(txhex) {
var deferred = Q.defer();
var args = {
data: { "txHex": txhex },
headers:{"Content-Type": "application/json"}
}
try{
client.methods.broadcasttx(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("getTransastion:(200)");
deferred.resolve([data]);
}
else if(data) {
console.log("getTransastion: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("getTransastion: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e) }
return deferred.promise;
}
coluutils.requestParseTx = function requestParseTx(txid)
{
var deferred = Q.defer();
var args = {
data: { "txid": txid },
headers:{"Content-Type": "application/json"}
}
try{
client.methods.preparsetx(args, function (data, response) {
console.log(data);
if (response.statusCode == 200) {
console.log("requestParseTx:(200) ");
deferred.resolve(safeParse(data));
}
else if(data) {
console.log("requestParseTx: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("requestParseTx: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e) }
return deferred.promise;
}
function getAssetInfo(assetId, utxo, verbosity)
{
var deferred = Q.defer();
var args = {
path: { "assetId": assetId, "utxo": utxo, "verbosity": verbosity },
headers:{"Content-Type": "application/json"}
}
try{
client.methods.getassetinfo(args, function (data, response) {
console.log(data.toString());
if (response.statusCode == 200) {
console.log("getAssetInfo:(200) ");
deferred.resolve(safeParse(data));
}
else if(data) {
console.log("getassetinfo: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(response.statusCode + " " + data));
}
else {
console.log("getassetinfo: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e); deferred.reject(new Error("error parsing respnse form blockexplorer")); }
return deferred.promise;
}
function getUnspentsByAddress(addresses)
{
var deferred = Q.defer();
addresses = _.uniq(addresses)
var args = {
data: {"addresses" : addresses },
headers:{"Content-Type": "application/json"}
}
try{
client.methods.getaddressutxos(args, function (data, response) {
console.log(data.toString());
if (response.statusCode == 200) {
console.log("getUnspentsByAddress:(200) ");
deferred.resolve(data);
}
else if(data) {
console.log("getUnspentsByAddress: rejecting with: " + response.statusCode + " " + data);
deferred.reject(new Error(JSON.stringify(data, null, 2)));
}
else {
console.log("getUnspentsByAddress: rejecting with: " + response.statusCode);
deferred.reject(new Error("Status code was " + response.statusCode));
}
}).on('error', function (err) {
console.log('something went wrong on the request', err.request.options);
deferred.reject(new Error("Status code was " + err.request.options));
});
}
catch(e) { console.log(e); deferred.reject(new Error("error parsing respnse form blockexplorer")); }
return deferred.promise;
}
//TODO: break this into a generic fee mechanisem where fee and and total inputs amount are diffrent
// inputs amount can be taked from the sent asset as well, fee variable is missleading
function comupteCost(withfee, metadata ){
fee = withfee ? config.minfee : 0;
if(metadata.to && metadata.to.length)
{
metadata.to.forEach(function(to) {
fee += config.mindustvalue
})
}
if(metadata.rules || metadata.metadata)
fee += config.writemultisig ? config.mindustvaluemultisig : 0;
fee += config.mindustvalue
console.log("comupteCost: " + fee)
return fee
}
function addInputsForSendTransaction(tx, metadata) {
var deferred = Q.defer()
var satoshiCost = comupteCost(true, metadata)
var totalInputs = { amount: 0 }
var reedemScripts = []
var coloredOutputIndexes = []
console.log('addInputsForSendTransaction')
try{
if(metadata.from || metadata.sendutxo) {
getUnspentArrayByAddressOrUtxo(metadata.from, metadata.sendutxo)
.then(function(utxos){
if(metadata.from)
console.log('got unspents for address: ' + metadata.from + " from block explorer")
else {
console.log('got unspent from parmameter: ' + metadata.sendutxo + " from block explorer")
if (utxos[0] && utxos[0].scriptPubKey && utxos[0].scriptPubKey.addresses && utxos[0].scriptPubKey.addresses[0])
metadata.from = utxos[0].scriptPubKey.addresses[0]
}
var assetList = []
metadata.to.forEach(function(to) {
console.log(to.assetId)
if(!assetList[to.assetId])
assetList[to.assetId] = { amount: 0, addresses: [], done: false, change: 0, encodeAmount: 0, inputs: [] }
assetList[to.assetId].amount += to.amount
assetList[to.assetId].encodeAmount = assetList[to.assetId].amount;
// generate a multisig adress, remeber to return the reedem scripts
if(!to.address && to.pubKeys && to.m) {
var multisig = generateMultisigAddress(to.pubKeys, to.m)
assetList[to.assetId].addresses.push({ address: multisig.address, amount: to.amount, reedemScript: multisig.reedemScript})
}
else
assetList[to.assetId].addresses.push({ address: to.address, amount: to.amount})
})
console.log('finshed creating per asset list')
for( var asset in assetList)
{
console.log('working on asset: ' + asset)
console.log(utxos)
var assetUtxos = utxos.filter(function (element, index, array) {
if (!element.assets) { return false }
return element.assets.some(function(a){
console.log('checking ' + a.assetId + ' and '+ asset)
return (a.assetId == asset)
})
})
if(assetUtxos && assetUtxos.length > 0) {
console.log("have utxo list")
var key = asset;
assetUtxos.forEach(function (utxo){ if(utxo.used) {