Created
June 14, 2012 22:23
-
-
Save anfedorov/2933373 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ElectrumAddressGenerator = function () { | |
var curve = getSECCurveByName("secp256k1"), | |
G = curve.getG(); | |
function big_int_hash(n, forChange, pubKey) { | |
return BigInteger.fromByteArrayUnsigned( | |
Crypto.SHA256( | |
Crypto.SHA256( | |
Crypto.charenc.UTF8.stringToBytes( | |
n + ':' + Number(forChange) + ':' | |
).concat(pubKey.slice(1)), | |
{asBytes: true} | |
), | |
{asBytes: true} | |
) | |
); | |
} | |
function pt_to_addr(pt) { | |
return new Bitcoin.Address(Bitcoin.Util.sha256ripe160(pt.getEncoded())); | |
} | |
return { | |
"gen": function (master_pub_key, master_priv_key, n, isChange) { | |
var pt_master_pub = ECPointFp.decodeFrom(curve.getCurve(), master_pub_key), | |
a = big_int_hash(n, isChange, master_pub_key), | |
pt_new_pub = pt_master_pub.add(G.multiply(a)); | |
if (master_priv_key) { | |
var order = curve.getN(), | |
new_priv_key = BigInteger.fromByteArrayUnsigned(master_priv_key).add(a).mod(order), | |
new_priv_addr = new Bitcoin.Address(new_priv_key.toByteArrayUnsigned()); | |
new_priv_addr.version = 128; | |
} | |
return [pt_to_addr(pt_new_pub).toString(), new_priv_addr ? new_priv_addr.toString() : ""]; | |
}, | |
"priv_to_pub": function (priv_key) { | |
var secexp = BigInteger.fromByteArrayUnsigned(priv_key); | |
return G.multiply(secexp).getEncoded(); | |
}, | |
"seed_to_priv": function (str_seed) { | |
var first_seed = Crypto.charenc.UTF8.stringToBytes(str_seed), | |
seed = first_seed; | |
for (var i=0; i < 100000; i++) { | |
seed = Crypto.SHA256(seed.concat(first_seed), {asBytes: true}); | |
} | |
return seed; | |
} | |
} | |
}; | |
function ElectrumAddressGenerator_test() { | |
var eag = ElectrumAddressGenerator(), | |
master_priv_key = eag.seed_to_priv("12345678"), | |
master_pub_key = eag.priv_to_pub(master_priv_key); | |
for (var i=0; i < 10; i++) { | |
console.log("Address " + i + ":", eag.gen(master_pub_key, master_priv_key, i, false)); | |
} | |
for (var i=0; i < 10; i++) { | |
console.log("Change address " + i + ":", eag.gen(master_pub_key, master_priv_key, i, true)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment