Skip to content

Instantly share code, notes, and snippets.

@justmoon
Created September 27, 2011 01:14
Show Gist options
  • Save justmoon/45f49a96669ccb016460 to your computer and use it in GitHub Desktop.
Save justmoon/45f49a96669ccb016460 to your computer and use it in GitHub Desktop.
Browser side payment signing in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Browser side payment signing in JavaScript</title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.8.4/socket.io.min.js"></script>
<script type="text/javascript" src="http://cdn.bitcoinjs.org/libs/bitcoinjs-lib/latest/bitcoinjs-min.js"></script>
<script type="text/javascript" src="http://cdn.bitcoinjs.org/libs/bitcoinjs-lib/latest/bitcoinjs-exit-min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
// Inputs
var keyBase58 = "E1FrLybWP4VMjprCThjsvvQSCK4KYeuZtoTdsXWWk9uF";
var toAddr = "1Dw9tmAfJoMmYTCaGuvZTiULhccparxZ4S";
var value = "0.01";
var fee = "0.0005";
// Key
var key = new Bitcoin.ECKey(Bitcoin.Base58.decode(keyBase58));
var addr = key.getBitcoinAddress().toString();
// If the key was in hex, you would use Bitcoin.Util.hexToBytes instead of
// Bitcoin.Base58.decode. In the future, we may have a "smart parser"
// detecting the format automagically.
// Get transactions
var exit = new Bitcoin.ExitNode("exit.trucoin.com", 3125, /* SSL= */ true);
exit.query('pubkeys/register', {keys: addr}, true, function (res) {
exit.query('pubkeys/gettxs', {handle: res.handle}, true, function (res) {
// Create wallet
var wallet = new Bitcoin.Wallet();
wallet.addKey(key);
for (var i = 0, l = res.txs.length; i < l; i++) {
wallet.process(new Bitcoin.Transaction(res.txs[i]));
}
// If you wanted to print out the balance you could do it like so:
// var balance = Bitcoin.util.formatValue(wallet.getBalance());
// Create transaction
var toAddrObj = new Bitcoin.Address(toAddr);
var valBigInt = Bitcoin.Util.parseValue(value);
var feeBigInt = Bitcoin.Util.parseValue(fee);
var tx = wallet.createSend(toAddrObj, valBigInt, feeBigInt);
// Serialize transaction
var txBase64 = Bitcoin.Util.bytesToBase64(tx.serialize());
// Submit transaction
exit.query('tx/send', {tx: txBase64}, true, function (e) {
if (e.success) {
// Successfully sent
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment