diff --git a/example/index.js b/example/index.js index 7997a746..4cfc8c0d 100755 --- a/example/index.js +++ b/example/index.js @@ -36,6 +36,10 @@ bitcoind.start(function(err) { }); })(genesisBlock); }, 1000); + bitcoind.on('block', function(block) { + console.log('Found block'); + console.log('Next: %s', block.nextblockhash); + }); }); }); diff --git a/lib/bitcoind.js b/lib/bitcoind.js index a72017aa..16beac21 100644 --- a/lib/bitcoind.js +++ b/lib/bitcoind.js @@ -128,6 +128,14 @@ Bitcoin.prototype.start = function(callback) { } }, 1000); + bitcoindjs.onBlock(function(block) { + self.emit('block', block); + }); + + bitcoindjs.onTx(function(tx) { + self.emit('tx', tx); + }); + if (this.log_pipe !== -1) { this.log('log pipe opened: %d', this.log_pipe); this._pipe = new net.Socket(this.log_pipe); diff --git a/src/bitcoindjs.cc b/src/bitcoindjs.cc index 37dd35f6..f20c8823 100644 --- a/src/bitcoindjs.cc +++ b/src/bitcoindjs.cc @@ -123,6 +123,8 @@ NAN_METHOD(IsStopped); NAN_METHOD(StopBitcoind); NAN_METHOD(GetBlock); NAN_METHOD(GetTx); +NAN_METHOD(OnBlock); +NAN_METHOD(OnTx); static void async_start_node_work(uv_work_t *req); @@ -1078,6 +1080,72 @@ async_get_tx_after(uv_work_t *req) { delete req; } +/** + * OnBlock(callback) + * bitcoind.onBlock(callback) + */ + +NAN_METHOD(OnBlock) { + NanScope(); + + if (args.Length() < 1 || !args[0]->IsFunction()) { + return NanThrowError( + "Usage: bitcoindjs.onBlock(callback)"); + } + + Local callback = Local::Cast(args[0]); + + Persistent cb; + cb = Persistent::New(callback); + + Local block = NanNew(); + + const unsigned argc = 1; + Local argv[argc] = { + Local::New(block) + }; + TryCatch try_catch; + cb->Call(Context::GetCurrent()->Global(), argc, argv); + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + + NanReturnValue(Undefined()); +} + +/** + * OnTx(callback) + * bitcoind.onTx(callback) + */ + +NAN_METHOD(OnTx) { + NanScope(); + + if (args.Length() < 1 || !args[0]->IsFunction()) { + return NanThrowError( + "Usage: bitcoindjs.onTx(callback)"); + } + + Local callback = Local::Cast(args[0]); + + Persistent cb; + cb = Persistent::New(callback); + + Local tx = NanNew(); + + const unsigned argc = 1; + Local argv[argc] = { + Local::New(tx) + }; + TryCatch try_catch; + cb->Call(Context::GetCurrent()->Global(), argc, argv); + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + + NanReturnValue(Undefined()); +} + /** * Init */ @@ -1091,6 +1159,8 @@ init(Handle target) { NODE_SET_METHOD(target, "stopped", IsStopped); NODE_SET_METHOD(target, "getBlock", GetBlock); NODE_SET_METHOD(target, "getTx", GetTx); + NODE_SET_METHOD(target, "onBlock", OnBlock); + NODE_SET_METHOD(target, "onTx", OnTx); } NODE_MODULE(bitcoindjs, init)