bitcoinjs-lib/src/address.js

58 lines
1.3 KiB
JavaScript
Raw Normal View History

2011-05-04 18:02:56 +02:00
Bitcoin.Address = function (bytes) {
2012-01-11 02:40:45 +01:00
if ("string" == typeof bytes) {
bytes = Bitcoin.Address.decodeString(bytes);
}
this.hash = bytes;
2011-05-08 12:48:54 +02:00
2012-01-11 02:40:45 +01:00
this.version = 0x00;
2011-05-04 18:02:56 +02:00
};
2012-01-11 10:41:52 +01:00
/**
* Serialize this object as a standard Bitcoin address.
*
* Returns the address as a base58-encoded string in the standardized format.
*/
2011-05-04 18:02:56 +02:00
Bitcoin.Address.prototype.toString = function () {
2012-01-11 02:40:45 +01:00
// Get a copy of the hash
var hash = this.hash.slice(0);
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
// Version
hash.unshift(this.version);
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
var bytes = hash.concat(checksum.slice(0,4));
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
return Bitcoin.Base58.encode(bytes);
2011-05-04 18:02:56 +02:00
};
Bitcoin.Address.prototype.getHashBase64 = function () {
2012-01-11 02:40:45 +01:00
return Crypto.util.bytesToBase64(this.hash);
2011-05-04 18:02:56 +02:00
};
2012-01-11 10:41:52 +01:00
/**
* Parse a Bitcoin address contained in a string.
*/
2011-05-04 18:02:56 +02:00
Bitcoin.Address.decodeString = function (string) {
2012-01-11 02:40:45 +01:00
var bytes = Bitcoin.Base58.decode(string);
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
var hash = bytes.slice(0, 21);
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
if (checksum[0] != bytes[21] ||
checksum[1] != bytes[22] ||
checksum[2] != bytes[23] ||
checksum[3] != bytes[24]) {
throw "Checksum validation failed!";
}
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
var version = hash.shift();
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
if (version != 0) {
throw "Version "+version+" not supported!";
}
2011-05-04 18:02:56 +02:00
2012-01-11 02:40:45 +01:00
return hash;
2011-05-04 18:02:56 +02:00
};