forked from bcosorg/bcos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb3sync.js
744 lines (634 loc) · 19.3 KB
/
web3sync.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
//var Tx = require('./transactionObject.js');
//const ethUtil = require('./utils.js')
const secp256k1 = require('secp256k1')
const createKeccakHash = require('keccak')
const assert = require('assert')
const rlp = require('rlp')
const BN = require('bn.js')
const fs=require('fs');
const execSync =require('child_process').execSync;
const coder = require('./codeUtils');
var config=require('./config');
/*
var addressjson={};
try{
addressjson= JSON.parse(fs.readFileSync(config.Ouputpath+'address.json'));
}catch(e){
console.log(e);
}*/
function privateToPublic(privateKey) {
privateKey = toBuffer(privateKey)
// skip the type flag and use the X, Y points
return secp256k1.publicKeyCreate(privateKey, false).slice(1)
}
function privateToAddress(privateKey) {
return publicToAddress(privateToPublic(privateKey))
}
function publicToAddress(pubKey, sanitize) {
pubKey = toBuffer(pubKey)
if (sanitize && (pubKey.length !== 64)) {
pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1)
}
assert(pubKey.length === 64)
// Only take the lower 160bits of the hash
return sha3(pubKey).slice(-20)
}
function toBuffer(v) {
if (!Buffer.isBuffer(v)) {
if (Array.isArray(v)) {
v = Buffer.from(v)
} else if (typeof v === 'string') {
if (isHexPrefixed(v)) {
v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex')
} else {
v = Buffer.from(v)
}
} else if (typeof v === 'number') {
v = intToBuffer(v)
} else if (v === null || v === undefined) {
v = Buffer.allocUnsafe(0)
} else if (v.toArray) {
// converts a BN to a Buffer
v = Buffer.from(v.toArray())
} else {
throw new Error('invalid type')
}
}
return v
}
function isHexPrefixed(str) {
return str.slice(0, 2) === '0x'
}
function padToEven(a) {
if (a.length % 2) a = '0' + a
return a
}
function stripHexPrefix(str) {
if (typeof str !== 'string') {
return str
}
return isHexPrefixed(str) ? str.slice(2) : str
}
function intToBuffer(i) {
var hex = intToHex(i)
return Buffer.from(hex.slice(2), 'hex')
}
function intToHex(i) {
assert(i % 1 === 0, 'number is not a integer')
assert(i >= 0, 'number must be positive')
var hex = i.toString(16)
if (hex.length % 2) {
hex = '0' + hex
}
return '0x' + hex
}
function setLength(msg, length, right) {
var buf = zeros(length)
msg = toBuffer(msg)
if (right) {
if (msg.length < length) {
msg.copy(buf)
return buf
}
return msg.slice(0, length)
} else {
if (msg.length < length) {
msg.copy(buf, length - msg.length)
return buf
}
return msg.slice(-length)
}
}
function sha3(a, bits) {
a = toBuffer(a)
if (!bits) bits = 256
return createKeccakHash('keccak' + bits).update(a).digest()
}
function baToJSON(ba) {
if (Buffer.isBuffer(ba)) {
return '0x' + ba.toString('hex')
} else if (ba instanceof Array) {
var array = []
for (var i = 0; i < ba.length; i++) {
array.push(baToJSON(ba[i]))
}
return array
}
}
function zeros(bytes) {
return Buffer.allocUnsafe(bytes).fill(0)
}
function stripZeros(a) {
a = stripHexPrefix(a)
var first = a[0]
while (a.length > 0 && first.toString() === '0') {
a = a.slice(1)
first = a[0]
}
return a
}
function defineProperties(self, fields, data) {
self.raw = []
self._fields = []
// attach the `toJSON`
self.toJSON = function (label) {
if (label) {
var obj = {}
self._fields.forEach(function (field) {
obj[field] = '0x' + self[field].toString('hex')
})
return obj
}
return baToJSON(this.raw)
}
self.serialize = function serialize () {
return rlp.encode(self.raw)
}
fields.forEach(function (field, i) {
self._fields.push(field.name)
function getter () {
return self.raw[i]
}
function setter (v) {
v = toBuffer(v)
if (v.toString('hex') === '00' && !field.allowZero) {
v = Buffer.allocUnsafe(0)
}
if (field.allowLess && field.length) {
v = stripZeros(v)
assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes')
} else if (!(field.allowZero && v.length === 0) && field.length) {
assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length)
}
self.raw[i] = v
}
Object.defineProperty(self, field.name, {
enumerable: true,
configurable: true,
get: getter,
set: setter
})
if (field.default) {
self[field.name] = field.default
}
// attach alias
if (field.alias) {
Object.defineProperty(self, field.alias, {
enumerable: false,
configurable: true,
set: setter,
get: getter
})
}
})
// if the constuctor is passed data
if (data) {
if (typeof data === 'string') {
data = Buffer.from(stripHexPrefix(data), 'hex')
}
if (Buffer.isBuffer(data)) {
data = rlp.decode(data)
}
if (Array.isArray(data)) {
if (data.length > self._fields.length) {
throw (new Error('wrong number of fields in data'))
}
// make sure all the items are buffers
data.forEach(function (d, i) {
self[self._fields[i]] = toBuffer(d)
})
} else if (typeof data === 'object') {
const keys = Object.keys(data)
fields.forEach(function (field) {
if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]
if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]
})
} else {
throw new Error('invalid data')
}
}
}
function bufferToInt(buf) {
return new BN(toBuffer(buf)).toNumber()
}
function rlphash(a) {
return sha3(rlp.encode(a))
}
function ecrecover(msgHash, v, r, s) {
var signature = Buffer.concat([setLength(r, 32), setLength(s, 32)], 64)
var recovery = v - 27
if (recovery !== 0 && recovery !== 1) {
throw new Error('Invalid signature v value')
}
var senderPubKey = secp256k1.recover(msgHash, signature, recovery)
return secp256k1.publicKeyConvert(senderPubKey, false).slice(1)
}
function ecsign(msgHash, privateKey) {
var sig = secp256k1.sign(msgHash, privateKey)
var ret = {}
ret.r = sig.signature.slice(0, 32)
ret.s = sig.signature.slice(32, 64)
ret.v = sig.recovery + 27
return ret
}
//const BN = ethUtil.BN
// secp256k1n/2
const N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16)
function Transaction(data) {
data = data || {}
// Define Properties
const fields = [{
name: 'randomid',
length: 32,
allowLess: true,
default: new Buffer([])
}, {
name: 'gasPrice',
length: 32,
allowLess: true,
default: new Buffer([])
}, {
name: 'gasLimit',
alias: 'gas',
length: 32,
allowLess: true,
default: new Buffer([])
}, {
name: 'blockLimit',
length: 32,
allowLess: true,
default: new Buffer([])
},{
name: 'to',
allowZero: true,
length: 20,
default: new Buffer([])
}, {
name: 'value',
length: 32,
allowLess: true,
default: new Buffer([])
}, {
name: 'data',
alias: 'input',
allowZero: true,
default: new Buffer([])
}, {
name: 'v',
length: 1,
default: new Buffer([0x1c])
}, {
name: 'r',
length: 32,
allowLess: true,
default: new Buffer([])
}, {
name: 's',
length: 32,
allowLess: true,
default: new Buffer([])
}]
/**
* Returns the rlp encoding of the transaction
* @method serialize
* @return {Buffer}
*/
// attached serialize
defineProperties(this, fields, data)
/**
* @prop {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters.
*/
Object.defineProperty(this, 'from', {
enumerable: true,
configurable: true,
get: this.getSenderAddress.bind(this)
})
// calculate chainId from signature
var sigV = bufferToInt(this.v)
var chainId = Math.floor((sigV - 35) / 2)
if (chainId < 0) chainId = 0
// set chainId
this._chainId = chainId || data.chainId || 0
this._homestead = true
}
/**
* If the tx's `to` is to the creation address
* @return {Boolean}
*/
Transaction.prototype.toCreationAddress=function () {
return this.to.toString('hex') === ''
}
/**
* Computes a sha3-256 hash of the serialized tx
* @param {Boolean} [includeSignature=true] whether or not to inculde the signature
* @return {Buffer}
*/
Transaction.prototype.hash=function (includeSignature) {
if (includeSignature === undefined) includeSignature = true
// backup original signature
const rawCopy = this.raw.slice(0)
// modify raw for signature generation only
if (this._chainId > 0) {
includeSignature = true
this.v = this._chainId
this.r = 0
this.s = 0
}
// generate rlp params for hash
//console.log(this.raw.length)
var txRawForHash = includeSignature ? this.raw : this.raw.slice(0, this.raw.length - 3)
//var txRawForHash = includeSignature ? this.raw : this.raw.slice(0, 7)
// restore original signature
this.raw = rawCopy.slice()
// create hash
return rlphash(txRawForHash)
}
/**
* returns the public key of the sender
* @return {Buffer}
*/
Transaction.prototype.getChainId=function() {
return this._chainId
}
/**
* returns the sender's address
* @return {Buffer}
*/
Transaction.prototype.getSenderAddress = function() {
if (this._from) {
return this._from
}
const pubkey = this.getSenderPublicKey()
this._from = publicToAddress(pubkey)
return this._from
}
/**
* returns the public key of the sender
* @return {Buffer}
*/
Transaction.prototype.getSenderPublicKey =function() {
if (!this._senderPubKey || !this._senderPubKey.length) {
if (!this.verifySignature()) throw new Error('Invalid Signature')
}
return this._senderPubKey
}
/**
* Determines if the signature is valid
* @return {Boolean}
*/
Transaction.prototype.verifySignature =function() {
const msgHash = this.hash(false)
// All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid.
if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) {
return false
}
try {
var v = bufferToInt(this.v)
if (this._chainId > 0) {
v -= this._chainId * 2 + 8
}
this._senderPubKey = ecrecover(msgHash, v, this.r, this.s)
} catch (e) {
return false
}
return !!this._senderPubKey
}
/**
* sign a transaction with a given a private key
* @param {Buffer} privateKey
*/
Transaction.prototype.sign =function(privateKey) {
const msgHash = this.hash(false)
const sig = ecsign(msgHash, privateKey)
if (this._chainId > 0) {
sig.v += this._chainId * 2 + 8
}
Object.assign(this, sig)
}
/**
* The amount of gas paid for the data in this tx
* @return {BN}
*/
Transaction.prototype.getDataFee=function() {
const data = this.raw[5]
const cost = new BN(0)
for (var i = 0; i < data.length; i++) {
data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v)
}
return cost
}
/**
* the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)
* @return {BN}
*/
Transaction.prototype.getBaseFee =function() {
const fee = this.getDataFee().iaddn(fees.txGas.v)
if (this._homestead && this.toCreationAddress()) {
fee.iaddn(fees.txCreation.v)
}
return fee
}
/**
* the up front amount that an account must have for this transaction to be valid
* @return {BN}
*/
Transaction.prototype.getUpfrontCost =function() {
return new BN(this.gasLimit)
.imul(new BN(this.gasPrice))
.iadd(new BN(this.value))
}
/**
* validates the signature and checks to see if it has enough gas
* @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean
* @return {Boolean|String}
*/
Transaction.prototype.validate =function(stringError) {
const errors = []
if (!this.verifySignature()) {
errors.push('Invalid Signature')
}
if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) {
errors.push([`gas limit is to low. Need at least ${this.getBaseFee()}`])
}
if (stringError === undefined || stringError === false) {
return errors.length === 0
} else {
return errors.join(' ')
}
}
//exports.Transaction=Transaction;
function signTransaction(tx_data,privKey,callback)
{
// convert string private key to a Buffer Object
var privateKey = new Buffer(privKey, 'hex');
var tx = new Transaction(tx_data);
tx.sign(privateKey);
// Build a serialized hex version of the Tx
var serializedTx = '0x' + tx.serialize().toString('hex');
if( null !== callback)
{
callback(serializedTx);
return ;
}
else
{
return serializedTx;
}
}
//exports.signTransaction=signTransaction;
/*
async function deploy(args,account, filename) {
try{
execSync("solc --abi --bin -o " + config.Ouputpath + " " + filename + ".sol" + " &>/dev/null");
//console.log('编译成功!');
} catch(e){
console.log('编译失败!' + e);
}
var abi=JSON.parse(fs.readFileSync(config.Ouputpath+filename+".sol:"+filename+'.abi', 'utf-8'));
var binary=fs.readFileSync(config.Ouputpath+filename+'.bin', 'utf-8');
var contract = web3.eth.contract(abi);
var initializer = {from: account, data: binary};
initializer.randomid=Math.ceil(Math.random()*100000000);
return new Promise((resolve, reject) => {
var callback = function(e, contract){
if(!e) {
if(!contract.address) {
//console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");
} else {
console.log(filename+"合约地址 "+contract.address);
addressjson[filename]= contract.address;
fs.writeFileSync(config.Ouputpath+'address.json', JSON.stringify(addressjson), 'utf-8');
var deployfilename=filename+'.deploy.js';
fs.writeFileSync(config.Ouputpath+filename+'.deploy', JSON.stringify({"address":contract.address,"abi":contract.abi}), 'utf-8');
var now2=new Date();
var endtime=now2.getTime();
resolve(contract);
}
}
else
{
console.log("Has Error"+e);
}
};
var now=new Date();
var starttime=now.getTime();
//部署到网络
var newcontract=contract.new;
//部署到网络
//var token = contract.new(args,initializer, callback);
args.push(initializer);
args.push(callback);
var token = newcontract.apply(contract,args);
});
}*/
async function getBlockNumber() {
return new Promise((resolve, reject) => {
web3.eth.getBlockNumber(function(e,d){
//console.log(e+',blocknumber='+d);
resolve(d);
});
});
}
function checkForTransactionResult(hash, callback){
var count = 0,
callbackFired = false;
// wait for receipt
//var filter = contract._eth.filter('latest', function(e){
var filter = web3.eth.filter('latest', function(e){
if (!e && !callbackFired) {
count++;
// stop watching after 50 blocks (timeout)
if (count > 50) {
filter.stopWatching(function() {});
callbackFired = true;
if (callback) {
callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
} else {
throw new Error('Contract transaction couldn\'t be found after 50 blocks');
}
} else {
web3.eth.getTransactionReceipt(hash, function(e, receipt){
if(receipt && !callbackFired) {
//console.log(receipt);
callback(null, receipt);
filter.stopWatching(function() {});
}
});
}
}
});
};
async function unlockAccount(account, password) {
return new Promise((resolve, reject) => {
web3.personal.unlockAccount(account,"123",1,function(err,data){
resolve(data);
})
});
}
async function rawDeploy(account, privateKey,filename) {
var binary=fs.readFileSync(config.Ouputpath+"./"+filename+".bin",'utf-8');
var postdata = {
input: "0x"+binary,
from: account,
to: null,
gas: 100000000,
randomid:Math.ceil(Math.random()*100000000),
blockLimit:await getBlockNumber() + 1000,
}
var signTX = signTransaction(postdata, privateKey, null);
return new Promise((resolve, reject) => {
web3.eth.sendRawTransaction(signTX, function(err, address) {
if (!err) {
//console.log("发送交易成功: " + address);
checkForTransactionResult(address, (err, receipt) => {
var addressjson={};
if( receipt.contractAddress ){
console.log(filename+"合约地址 "+receipt.contractAddress);
fs.writeFileSync(config.Ouputpath+filename+'.address', receipt.contractAddress, 'utf-8');
}//if
resolve(receipt);
return;
});
return;
}
else {
console.log("发送交易失败!",err);
return;
}
});
});
}
async function sendRawTransaction(account, privateKey, to, func, params) {
var r = /^\w+\((.+)\)$/g.exec(func);
var types = r[1].split(',');
var tx_data = coder.codeTxData(func,types,params);
var postdata = {
data: tx_data,
from: account,
to: to,
gas: 1000000,
randomid:Math.ceil(Math.random()*100000000),
blockLimit:await getBlockNumber() + 1000,
}
var signTX = signTransaction(postdata, privateKey, null);
return new Promise((resolve, reject) => {
web3.eth.sendRawTransaction(signTX, function(err, address) {
if (!err) {
console.log("发送交易成功: " + address);
checkForTransactionResult(address, (err, receipt) => {
resolve(receipt);
});
//resolve(address);
}
else {
console.log("发送交易失败!",err);
return;
}
});
});
}
exports.getBlockNumber=getBlockNumber;
exports.sendRawTransaction=sendRawTransaction;
exports.unlockAccount=unlockAccount;
exports.rawDeploy=rawDeploy;
//exports.deploy=deploy;