@@ -2,6 +2,7 @@ var Readable = require('stream').Readable
2
2
var util = require ( 'util' )
3
3
var Inventory = require ( 'bitcore-p2p' ) . Inventory
4
4
var u = require ( './utils.js' )
5
+ var MerkleTree = require ( './merkleTree.js' )
5
6
6
7
var BlockStream = module . exports = function ( opts ) {
7
8
if ( ! opts . peer ) throw new Error ( '"peer" option is required for BlockStream' )
@@ -15,12 +16,17 @@ var BlockStream = module.exports = function (opts) {
15
16
this . from = opts . from || 0
16
17
this . to = opts . to || null
17
18
this . filtered = typeof opts . filtered === 'boolean' ? opts . filtered : ! ! this . peer . filter
19
+ this . fetchTransactions = typeof opts . fetchTransactions === 'boolean' ? opts . fetchTransactions : true
18
20
19
21
this . cursor = this . from
20
22
this . expected = null
21
23
this . ending = false
22
24
23
- this . peer . on ( this . filtered ? 'merkleblock' : 'block' , this . _onBlock . bind ( this ) )
25
+ if ( ! this . filtered ) {
26
+ this . peer . on ( 'block' , this . _onBlock . bind ( this ) )
27
+ } else {
28
+ this . peer . on ( 'merkleblock' , this . _onMerkleBlock . bind ( this ) )
29
+ }
24
30
}
25
31
util . inherits ( BlockStream , Readable )
26
32
@@ -55,7 +61,7 @@ BlockStream.prototype._getData = function (block) {
55
61
this . expected = { height : block . height , hash : hash }
56
62
var inventory = [
57
63
new Inventory ( {
58
- type : this . filtered ? Inventory . TYPE . MERKLE_BLOCK : Inventory . TYPE . BLOCK ,
64
+ type : this . filtered ? Inventory . TYPE . FILTERED_BLOCK : Inventory . TYPE . BLOCK ,
59
65
hash : hash
60
66
} )
61
67
]
@@ -64,16 +70,34 @@ BlockStream.prototype._getData = function (block) {
64
70
}
65
71
66
72
BlockStream . prototype . _onBlock = function ( message ) {
67
- if ( ! this . expected ) return
68
- var hash = u . toHash ( message . block . header . hash )
69
- if ( hash . compare ( this . expected . hash ) !== 0 ) return
70
- var block = {
73
+ this . _onData ( {
71
74
height : this . expected . height ,
72
75
header : message . block . header ,
73
76
block : message . block
74
- }
77
+ } )
78
+ }
79
+
80
+ BlockStream . prototype . _onMerkleBlock = function ( message ) {
81
+ if ( ! this . expected ) return
82
+
83
+ var tree = MerkleTree . fromMerkleBlock ( message . merkleBlock )
84
+
85
+ // TODO: fetch transactions
86
+
87
+ this . _onData ( {
88
+ height : this . expected . height ,
89
+ header : message . merkleBlock . header ,
90
+ tree : tree ,
91
+ transactions : [ ]
92
+ } )
93
+ }
94
+
95
+ BlockStream . prototype . _onData = function ( data ) {
96
+ if ( ! this . expected ) return
97
+ var hash = u . toHash ( data . header . hash )
98
+ if ( hash . compare ( this . expected . hash ) !== 0 ) return
75
99
this . expected = null
76
- var done = ! this . push ( block ) || this . ending
100
+ var done = ! this . push ( data ) || this . ending
77
101
if ( done ) this . _end ( )
78
102
else this . _next ( )
79
103
}
0 commit comments