add nonce support to WebRTC and Wallet

Each person keeps track of their own nonce, and the nonces of the other
copayers. The nonce is iterated for each message. If a person ever doesn't
iterate their nonce, that message is discarded by the copayers.

The nonces are saved as networkNonce (your nonce) and networkNonces (the nonces
of your copayers) in the wallet file.

In order to support restoring old wallets, the first four bytes of the 8 byte
nonce are actually the current time in seconds. Thus you can restore an old
wallet, because certainly at least one second has passed since your last
message. Only if you try to restore an old wallet within 1 second from the time
of your last message will you have a problem (or if your system clock is
grossly inaccurate).
This commit is contained in:
Ryan X. Charles 2014-07-08 23:03:30 -07:00
commit 88ab38eb00
6 changed files with 370 additions and 23 deletions

View file

@ -41,4 +41,55 @@ Network.prototype.peerFromCopayer = function(copayerId) {
return copayerId;
};
//hex version of one's own nonce
Network.prototype.setHexNonce = function(networkNonce) {
if (networkNonce && networkNonce.length === 16)
this.networkNonce = new Buffer(networkNonce, 'hex');
else
this.iterateNonce();
};
//hex version of copayers' nonces
Network.prototype.setHexNonces = function(networkNonces) {
for (var i in networkNonces) {
if (!this.networkNonces)
this.networkNonces = {};
if (networkNonces[i].length === 16)
this.networkNonces[i] = new Buffer(networkNonces[i], 'hex');
}
};
//for oneself
Network.prototype.getHexNonce = function() {
return this.networkNonce.toString('hex');
};
//for copayers
Network.prototype.getHexNonces = function() {
var networkNoncesHex = [];
for (var i in this.networkNonces) {
networkNoncesHex = this.networkNonces[i].toString('hex');
}
return networkNoncesHex;
};
Network.prototype.iterateNonce = function() {
if (!this.networkNonce || this.networkNonce.length !== 8) {
this.networkNonce = new Buffer(8);
this.networkNonce.fill(0);
this.networkNonce[7] = 1;
return this.networkNonce;
}
//the first 4 bytes of a nonce is a unix timestamp in seconds
//the second 4 bytes is just an iterated "sub" nonce
//the whole thing is interpreted as one big endian number
var noncep1 = this.networkNonce.slice(0, 4);
noncep1.writeUInt32BE(Math.floor(Date.now()/1000), 0);
var noncep2uint = this.networkNonce.slice(4, 8).readUInt32BE(0);
var noncep2 = this.networkNonce.slice(4, 8);
noncep2.writeUInt32BE(noncep2uint + 1, 0);
return this.networkNonce;
};
module.exports = require('soop')(Network);