forked from BitGo/BitGoJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathripple.js
More file actions
72 lines (64 loc) · 2.22 KB
/
Copy pathripple.js
File metadata and controls
72 lines (64 loc) · 2.22 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
const rippleKeypairs = require('ripple-keypairs');
const ripple = require('ripple-lib');
const prova = require('./prova');
const keypairs = require('ripple-keypairs');
const binary = require('ripple-binary-codec');
const { computeBinaryTransactionHash } = require('ripple-hashes');
function computeSignature(tx, privateKey, signAs) {
const signingData = signAs ?
binary.encodeForMultisigning(tx, signAs) : binary.encodeForSigning(tx);
return keypairs.sign(signingData, privateKey);
}
/**
* Sign Ripple transaction with a secp256k1 private key
* @param txHex
* @param privateKey
* @param options
* @returns {{signedTransaction: *, id}}
*/
const signWithPrivateKey = function(txHex, privateKey, options) {
let privateKeyBuffer = new Buffer(privateKey, 'hex');
if (privateKeyBuffer.length === 33 && privateKeyBuffer[0] === 0) {
privateKeyBuffer = privateKeyBuffer.slice(1, 33);
}
const privateKeyObject = prova.ECPair.fromPrivateKeyBuffer(privateKeyBuffer);
const publicKey = privateKeyObject.getPublicKeyBuffer().toString('hex').toUpperCase();
let tx;
try {
tx = binary.decode(txHex);
} catch (e) {
try {
tx = JSON.parse(txHex);
} catch (e) {
throw new Error('txHex needs to be either hex or JSON string for XRP');
}
}
if (tx.TxnSignature || tx.Signers) {
throw new Error('transaction must not contain "TxnSignature" or "Signers" properties');
}
tx.SigningPubKey = (options && options.signAs) ? '' : publicKey;
if (options && options.signAs) {
const expectedSigner = rippleKeypairs.deriveAddress(publicKey);
if (options.signAs !== expectedSigner) {
throw new Error('signAs does not match private key');
}
const signer = {
Account: options.signAs,
SigningPubKey: publicKey,
TxnSignature: computeSignature(tx, privateKey, options.signAs)
};
tx.Signers = [{ Signer: signer }];
} else {
tx.TxnSignature = computeSignature(tx, privateKey);
}
const serialized = binary.encode(tx);
return {
signedTransaction: serialized,
id: computeBinaryTransactionHash(serialized)
};
};
module.exports = (params) => {
const rippleLib = new ripple.RippleAPI(params);
rippleLib.signWithPrivateKey = signWithPrivateKey;
return rippleLib;
};