This repository has been archived by the owner on Sep 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
sign.js
66 lines (55 loc) · 1.95 KB
/
sign.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
'use strict';
var sjcl = require('ripple-lib').sjcl;
var Seed = require('ripple-lib').Seed;
var SerializedObject = require('ripple-lib').SerializedObject;
var validate = require('../lib/validate');
/**
* These prefixes are inserted before the source material used to
* generate various hashes. This is done to put each hash in its own
* "space." This way, two different types of objects with the
* same binary data will produce different hashes.
*
* Each prefix is a 4-byte value with the last byte set to zero
* and the first three bytes formed from the ASCII equivalent of
* some arbitrary string. For example "TXN".
*/
var HASH_TX_ID = 0x54584E00; // 'TXN'
var HASH_TX_SIGN = 0x53545800; // 'STX'
var HASH_TX_SIGN_TESTNET = 0x73747800; // 'stx'
function getKeyPair(address, secret) {
return Seed.from_json(secret).get_key(address);
}
function getPublicKeyHex(keypair) {
return keypair.to_hex_pub();
}
function serialize(txJSON) {
return SerializedObject.from_json(txJSON);
}
function hashSerialization(serialized, prefix) {
return serialized.hash(prefix || HASH_TX_ID).to_hex();
}
function hashJSON(txJSON, prefix) {
return hashSerialization(serialize(txJSON), prefix);
}
function signingHash(txJSON, isTestNet) {
return hashJSON(txJSON, isTestNet ? HASH_TX_SIGN_TESTNET : HASH_TX_SIGN);
}
function computeSignature(txJSON, keypair) {
var signature = keypair.sign(signingHash(txJSON));
return sjcl.codec.hex.fromBits(signature).toUpperCase();
}
function sign(txJSON, secret) {
validate.txJSON(txJSON);
validate.addressAndSecret({address: txJSON.Account, secret: secret});
var keypair = getKeyPair(txJSON.Acccount, secret);
if (txJSON.SigningPubKey === undefined) {
txJSON.SigningPubKey = getPublicKeyHex(keypair);
}
txJSON.TxnSignature = computeSignature(txJSON, keypair);
var serialized = serialize(txJSON);
return {
tx_blob: serialized.to_hex(),
hash: hashSerialization(serialized, HASH_TX_ID)
};
}
module.exports = sign;