Skip to content

Commit

Permalink
Change numToBytes to not rely on 32bit JS operators so that it can de…
Browse files Browse the repository at this point in the history
…al with larger numbers properly.
  • Loading branch information
mbelshe committed Apr 22, 2014
1 parent e60b3db commit fbc7377
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@ Bitcoin.Util = {
return array;
},

/**
* Turn an integer into a little-endian array of |length| bytes
*/
numToBytes: function(num, length) {
if (length === undefined) length = 8;
if (length === 0) return [];
return [num % 256].concat(this.numToBytes(Math.floor(num / 256), length - 1));
},

bytesToNum: function(bytes) {
var num = 0;
var factor = 1;
for (var i = 0; i < bytes.length; ++i) {
num += bytes[i] * factor;
factor *= 256;
}
return num;
},

/**
* Turn an integer into a "var_int".
*
Expand Down
13 changes: 13 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,26 @@ test("Decode MultiSig Input Script", function() {
module("Transaction");

test("Construction", function() {
Bitcoin.setNetwork('testnet');
var addrString = 'mgv5oJf5tv5YifH9xTuneRNEbRdG5ryocq';

var transaction = new Bitcoin.Transaction();
ok(transaction, "create");
transaction.addOutput(new Bitcoin.Address(addrString), 50);
transaction.addOutput(new Bitcoin.Address(addrString), 50*1e8);
transaction.addOutput(new Bitcoin.Address(addrString), 500*1e8);
transaction.addOutput(new Bitcoin.Address(addrString), 5000*1e8);
transaction.addOutput(new Bitcoin.Address(addrString), 500000*1e8);
var bytes = transaction.serialize();
ok(bytes, "serialize");
var tx2 = Bitcoin.Transaction.deserialize(bytes);
ok(tx2, "deserialize");
deepEqual(transaction.getHash(), tx2.getHash(), "deserialized matches tx");
equal(transaction.outs[0].value, 50, '50 satoshi output');
equal(transaction.outs[1].value, 50*1e8, '50 btc output');
equal(transaction.outs[2].value, 500*1e8, '500 btc output');
equal(transaction.outs[3].value, 5000*1e8, '5000 btc output');
equal(transaction.outs[4].value, 500000*1e8, '500000 btc output');
});

test("Add Input", function() {
Expand Down

0 comments on commit fbc7377

Please sign in to comment.