| 39 | var verackTimer = false; |
| 40 | |
| 41 | function tryLaunch(hosts) { |
| 42 | if (hosts.length == 0) { |
| 43 | console.log('out of potential connections...'); |
| 44 | return; |
| 45 | } |
| 46 | console.log('Finding new peer from pool of '+hosts.length+' potential peers'); |
| 47 | p = new Peer(hosts.pop(), 8444, 0xE9BEB4D9); |
| 48 | console.log('connecting to '+p.getUUID()); |
| 49 | |
| 50 | var hangupTimer = setTimeout(function() { // Give them a few seconds to respond, otherwise close the connection automatically |
| 51 | console.log('Peer never connected; hanging up'); |
| 52 | p.destroy(); |
| 53 | }, 5*1000); |
| 54 | hangupTimer.unref(); |
| 55 | |
| 56 | // Override message checksum to be SHA512 |
| 57 | p.messageChecksum = function(msg) { |
| 58 | var sha512 = crypto.createHash('sha512'); |
| 59 | sha512.update(msg); |
| 60 | return sha512.digest().slice(0,4); |
| 61 | } |
| 62 | |
| 63 | p.on('connect', function(d) { |
| 64 | console.log('connect'); |
| 65 | clearTimeout(hangupTimer); |
| 66 | |
| 67 | // Send VERSION message |
| 68 | var m = new Message(p.magicBytes, true); |
| 69 | m.putInt32(2); // version |
| 70 | m.putInt64(1); // services |
| 71 | m.putInt64(Math.round(new Date().getTime()/1000)); // timestamp |
| 72 | m.pad(26); // addr_me |
| 73 | m.pad(26); // addr_you |
| 74 | m.putInt64(0x1234); // nonce |
| 75 | m.putVarString('Node.js lite peer'); |
| 76 | m.putVarInt(1); // number of streams |
| 77 | m.putVarInt(1); // Stream I care about |
| 78 | |
| 79 | //console.log(m.raw().toString('hex')); |
| 80 | console.log('Sending VERSION message'); |
| 81 | verackTimeout = setTimeout(function() { |
| 82 | console.log('No VERACK received; disconnect'); |
| 83 | p.destroy(); |
| 84 | }, 10000); |
| 85 | verackTimeout.unref(); |
| 86 | p.once('verackMessage', function() { |
| 87 | console.log('VERACK received; this peer is active now'); |
| 88 | clearTimeout(verackTimeout); |
| 89 | }); |
| 90 | p.send('version', m.raw()); |
| 91 | }); |
| 92 | p.on('end', function(d) { |
| 93 | console.log('end'); |
| 94 | }); |
| 95 | p.on('error', function(d) { |
| 96 | console.log('error', d.error); |
| 97 | if (hosts.length > 0) tryLaunch(hosts); |
| 98 | }); |