Browse Source

Updated deterministic wallet; theoretically works now if properly combined with server

hk-custom-address
vub 11 years ago
parent
commit
1780f4a98f
  1. 4
      bitcoinjs-min.js
  2. 4
      src/bip32.js
  3. 18
      src/transaction.js
  4. 378
      src/wallet.js

4
bitcoinjs-min.js

File diff suppressed because one or more lines are too long

4
src/bip32.js

@ -75,9 +75,9 @@ BIP32key.prototype.ckd = function(i) {
if (i >= 2147483648) { if (i >= 2147483648) {
if (this.priv) throw new Error("Can't do private derivation on public key!") if (this.priv) throw new Error("Can't do private derivation on public key!")
blob = [0].concat(priv.slice(0,32),util.numToBytes(this.i,4).reverse()) blob = [0].concat(priv.slice(0,32),util.numToBytes(i,4).reverse())
} }
else blob = pub.concat(util.numToBytes(this.i,4).reverse()) else blob = pub.concat(util.numToBytes(i,4).reverse())
I = Crypto.HMAC(Crypto.SHA512,blob,this.chaincode,{ asBytes: true }) I = Crypto.HMAC(Crypto.SHA512,blob,this.chaincode,{ asBytes: true })

18
src/transaction.js

@ -110,21 +110,6 @@ Transaction.prototype.addOutput = function (address, value) {
})); }));
}; };
// TODO(shtylman) crypto sha uses this also
// Convert a byte array to big-endian 32-bit words
var bytesToWords = function (bytes) {
for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
words[b >>> 5] |= bytes[i] << (24 - b % 32);
return words;
};
// Convert big-endian 32-bit words to a byte array
var wordsToBytes = function (words) {
for (var bytes = [], b = 0; b < words.length * 32; b += 8)
bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
return bytes;
};
/** /**
* Serialize this transaction. * Serialize this transaction.
* *
@ -132,8 +117,7 @@ var wordsToBytes = function (words) {
* format. This method is byte-perfect, i.e. the resulting byte array can * format. This method is byte-perfect, i.e. the resulting byte array can
* be hashed to get the transaction's standard Bitcoin hash. * be hashed to get the transaction's standard Bitcoin hash.
*/ */
Transaction.prototype.serialize = function () Transaction.prototype.serialize = function () {
{
var buffer = []; var buffer = [];
buffer = buffer.concat(util.numToBytes(parseInt(this.version),4)); buffer = buffer.concat(util.numToBytes(parseInt(this.version),4));
buffer = buffer.concat(util.numToVarInt(this.ins.length)); buffer = buffer.concat(util.numToVarInt(this.ins.length));

378
src/wallet.js

@ -14,265 +14,157 @@ var TransactionOut = require('./transaction').TransactionOut;
var SecureRandom = require('./jsbn/rng'); var SecureRandom = require('./jsbn/rng');
var rng = new SecureRandom(); var rng = new SecureRandom();
var Wallet = function () { var Wallet = function (seed) {
// Keychain
// // Stored in a closure to make accidental serialization less likely
// The keychain is stored as a var in this closure to make accidental
// serialization less likely.
//
// Any functions accessing this value therefore have to be defined in
// the closure of this constructor.
var keys = []; var keys = [];
var masterkey = null; var masterkey = null;
var me = this;
// Public hashes of our keys // Addresses
this.addressHashes = []; this.addresses = [];
// Transaction data
this.txIndex = {};
this.unspentOuts = [];
// Other fields // Transaction output data
this.addressPointer = 0; this.outputs = {};
this.genMasterkey = function(seed) { // Make a new master key
this.newMasterKey = function(seed) {
if (!seed) { if (!seed) {
var seedBytes = new Array(32); var seedBytes = new Array(32);
rng.nextBytes(seedBytes); rng.nextBytes(seedBytes);
seed = conv.bytesToString(seedBytes) seed = conv.bytesToString(seedBytes)
} }
masterkey = new BIP32key(seed); masterkey = new BIP32key(seed);
keys = []
} }
this.newMasterKey(seed)
// Add a new address
this.generateAddress = function() { this.generateAddress = function() {
keys.push(masterkey.ckd(keys.length)) keys.push(masterkey.ckd(keys.length).key)
} this.addresses.push(keys[keys.length-1].getBitcoinAddress().toString())
return this.addresses[this.addresses.length - 1]
/** }
* Get the key chain.
* // Processes a transaction object
* Returns an array of hex-encoded private values. // If "verified" is true, then we trust the transaction as "final"
*/ this.processTx = function(tx, verified) {
this.getKeys = function () { var txhash = conv.bytesToHex(tx.getHash())
var keyExport = []; for (var i = 0; i < tx.outs.length; i++) {
if (this.addresses.indexOf(tx.outs[i].address.toString()) >= 0) {
for (var i = 0; i < keys.length; i++) { me.outputs[txhash+':'+i] = {
keyExport.push(keys[i].toString()); output: txhash+':'+i,
} value: tx.outs[i].value,
address: tx.outs[i].address.toString(),
return keyExport; timestamp: new Date().getTime() / 1000,
}; pending: true
}
this.privateSerialize = function() { }
return { }
masterkey: masterkey, for (var i = 0; i < tx.ins.length; i++) {
keys: this.getKeys() var op = tx.ins[i].outpoint
} var o = me.outputs[op.hash+':'+op.index]
} if (o) {
o.spend = txhash+':'+i
/** o.spendpending = true
* Get the public keys. o.timestamp = new Date().getTime() / 1000
* }
* Returns an array of hex-encoded public keys. }
*/ }
this.getPubKeys = function () { // Processes an output from an external source of the form
var pubs = []; // { output: txhash:index, value: integer, address: address }
// Excellent compatibility with SX and pybitcointools
for (var i = 0; i < keys.length; i++) { this.processOutput = function(o) {
pubs.push(conv.bytesToHex(keys[i].getPub())); if (!this.outputs[o.output] || this.outputs[o.output].pending)
} this.outputs[o.output] = o;
}
return pubs;
}; this.processExistingOutputs = function() {
var t = new Date().getTime() / 1000
/** for (var o in this.outputs) {
* Delete all keys. if (o.pending && t > o.timestamp + 1200)
*/ delete this.outputs[o]
this.clear = function () { if (o.spendpending && t > o.timestamp + 1200) {
keys = []; o.spendpending = false
masterkey = null; o.spend = false
}; delete o.timestamp
}
/** }
* Return the number of keys in this wallet. }
*/ var peoInterval = setInterval(this.processExistingOutputs, 10000)
this.getLength = function () {
return keys.length; this.getUtxoToPay = function(value) {
}; var h = []
for (var out in this.outputs) h.push(this.outputs[out])
/** var utxo = h.filter(function(x) { return !x.spend });
* Get the addresses for this wallet. var valuecompare = function(a,b) { return a.value > b.value; }
* var high = utxo.filter(function(o) { return o.value >= value; })
* Returns an array of Address objects. .sort(valuecompare);
*/ if (high.length > 0) return [high[0]];
this.getAllAddresses = function () { utxo.sort(valuecompare);
var addresses = []; var totalval = 0;
for (var i = 0; i < keys.length; i++) { for (var i = 0; i < utxo.length; i++) {
addresses.push(keys[i].getBitcoinAddress()); totalval += utxo[i].value;
} if (totalval >= value) return utxo.slice(0,i+1);
return addresses; }
}; throw ("Not enough money to send funds including transaction fee. Have: "
+ (totalval / 100000000) + ", needed: " + (value / 100000000));
this.getCurAddress = function () { }
if (keys[keys.length - 1]) {
return keys[keys.length - 1].getBitcoinAddress(); this.mkSend = function(to, value, fee) {
} else { var utxo = this.getUtxoToPay(value + fee)
return null; var sum = utxo.reduce(function(t,o) { return t + o.value },0),
} remainder = sum - value - fee
}; if (value < 5430) throw new Error("Amount below dust threshold!")
var unspentOuts = 0;
/** for (var o in this.outputs) {
* Sign a hash with a key. if (!this.outputs[o].spend) unspentOuts += 1
* if (unspentOuts >= 5) return
* This method expects the pubKeyHash as the first parameter and the hash }
* to be signed as the second parameter. var change = this.addresses[this.addresses.length - 1]
*/ var toOut = { address: to, value: value },
this.signWithKey = function (pubKeyHash, hash) { changeOut = { address: change, value: remainder }
pubKeyHash = conv.bytesToHex(pubKeyHash); halfChangeOut = { address: change, value: Math.floor(remainder/2) };
for (var i = 0; i < this.addressHashes.length; i++) {
if (this.addressHashes[i] == pubKeyHash) { var outs =
return keys[i].sign(hash); remainder < 5430 ? [toOut]
} : remainder < 10860 ? [toOut, changeOut]
} : unspentOuts == 5 ? [toOut, changeOut]
throw new Error("Missing key for signature"); : [toOut, halfChangeOut, halfChangeOut]
};
var tx = new Bitcoin.Transaction({
/** ins: utxo.map(function(x) { return x.output }),
* Retrieve the corresponding pubKey for a pubKeyHash. outs: outs
* })
* This function only works if the pubKey in question is part of this this.sign(tx)
* wallet. return tx
*/ }
this.getPubKeyFromHash = function (pubKeyHash) {
pubKeyHash = conv.bytesToHex(pubKeyHash); this.sign = function(tx) {
for (var i = 0; i < this.addressHashes.length; i++) { tx.ins.map(function(inp,i) {
if (this.addressHashes[i] == pubKeyHash) { var inp = inp.outpoint.hash+':'+inp.outpoint.index;
return keys[i].getPub(); if (me.outputs[inp]) {
} var address = me.outputs[inp].address,
} ind = me.addresses.indexOf(address);
throw new Error("Hash unknown"); if (ind >= 0) {
}; var key = keys[ind]
}; tx.sign(ind,key)
}
// return unspent transactions }
Wallet.prototype.unspentTx = function() { })
return this.unspentOuts; return tx;
}; }
/**
* Add a transaction to the wallet's processed transaction.
*
* This will add a transaction to the wallet, updating its balance and
* available unspent outputs.
*/
Wallet.prototype.process = function (tx) {
if (this.txIndex[tx.hash]) return;
var j;
var k;
var hash;
// Gather outputs
for (j = 0; j < tx.out.length; j++) {
var raw_tx = tx.out[j];
var txout = new TransactionOut(raw_tx);
// this hash is the hash of the pubkey which is the address the output when to
hash = conv.bytesToHex(txout.script.simpleOutPubKeyHash());
for (k = 0; k < this.addressHashes.length; k++) {
// if our address, then we add the unspent out to a list of unspent outputs
if (this.addressHashes[k] === hash) {
this.unspentOuts.push({tx: tx, index: j, output: txout});
break;
}
}
}
// Remove spent outputs
for (j = 0; j < tx.in.length; j++) {
var raw_tx = tx.in[j];
// mangle into the format TransactionIn expects
raw_tx.outpoint = {
hash: raw_tx.prev_out.hash,
index: raw_tx.prev_out.n
};
var txin = new TransactionIn(raw_tx);
var pubkey = txin.script.simpleInPubKey();
hash = conv.bytesToHex(util.sha256ripe160(pubkey));
for (k = 0; k < this.addressHashes.length; k++) {
if (this.addressHashes[k] === hash) {
for (var l = 0; l < this.unspentOuts.length; l++) {
if (txin.outpoint.hash == this.unspentOuts[l].tx.hash &&
txin.outpoint.index == this.unspentOuts[l].index) {
this.unspentOuts.splice(l, 1);
}
}
break;
}
}
}
// Index transaction
this.txIndex[tx.hash] = tx;
};
Wallet.prototype.getBalance = function () {
return this.unspentOuts.reduce(function(t,o) { return t + o.output.value },0);
};
Wallet.prototype.createSend = function (address, sendValue, feeValue) {
var selectedOuts = [];
var txValue = sendValue + feeValue;
var availableValue = 0;
var i;
for (i = 0; i < this.unspentOuts.length; i++) {
var txout = this.unspentOuts[i];
selectedOuts.push(txout);
availableValue += txout.output.value;
if (availableValue >= txValue) break;
}
if (availableValue < txValue) {
throw new Error('Insufficient funds.');
}
var changeValue = availableValue - txValue;
var sendTx = new Transaction();
for (i = 0; i < selectedOuts.length; i++) {
sendTx.addInput(selectedOuts[i].tx, selectedOuts[i].index);
}
sendTx.addOutput(address, sendValue);
if (changeValue > 0) {
sendTx.addOutput(this.getCurAddress(), changeValue);
}
var hashType = 1; // SIGHASH_ALL
sendTx.signWithKeys(this.getKeys(), selectedOuts, hashType)
return sendTx;
};
Wallet.prototype.clearTransactions = function () {
this.txIndex = {};
this.unspentOuts = [];
};
/** this.getMasterKey = function() { return masterkey }
* Check to see if a pubKeyHash belongs to this wallet.
*/
Wallet.prototype.hasHash = function (hash) {
if (util.isArray(hash)) hash = conv.bytesToHex(hash);
// TODO: Just create an object with hashes as keys for faster lookup this.getPrivateKey = function(index) {
for (var k = 0; k < this.addressHashes.length; k++) { if (typeof index == "string")
if (this.addressHashes[k] === hash) return true; return keys.filter(function(i,k){ return addresses[i] == index })[0]
} else
return false; return keys[index]
}
this.getPrivateKeys = function() { return keys }
}; };
module.exports = Wallet; module.exports = Wallet;

Loading…
Cancel
Save