From 26afbccc98ea44b113c9efef29a72d14c7e32cd2 Mon Sep 17 00:00:00 2001
From: Wei Lu <luwei.here@gmail.com>
Date: Sat, 22 Mar 2014 15:09:00 +0800
Subject: [PATCH] wallet allows setting unspent outputs

---
 src/wallet.js  | 17 +++++++++++++++++
 test/wallet.js | 39 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 56 insertions(+)

diff --git a/src/wallet.js b/src/wallet.js
index 63486cd..44c592e 100644
--- a/src/wallet.js
+++ b/src/wallet.js
@@ -80,6 +80,23 @@ var Wallet = function (seed, options) {
       return utxo
     }
 
+    this.setUnspentOutputs = function(utxo) {
+      var outputs = {}
+
+      utxo.forEach(function(o){
+        var hash = o.hash || convert.reverseEndian(o.hashLittleEndian)
+        var key = hash + ":" + o.outputIndex
+        outputs[key] = {
+          output: key,
+          scriptPubKey: o.scriptPubKey,
+          address: o.address,
+          value: o.value
+        }
+      })
+
+      this.outputs = outputs
+    }
+
     // Processes a transaction object
     // If "verified" is true, then we trust the transaction as "final"
     this.processTx = function(tx, verified) {
diff --git a/test/wallet.js b/test/wallet.js
index e02b10d..549cc70 100644
--- a/test/wallet.js
+++ b/test/wallet.js
@@ -172,6 +172,40 @@ describe('Wallet', function() {
         assert.deepEqual(wallet.getUnspentOutputs(), expectedUtxo)
       })
     })
+
+    describe('setUnspentOutputs', function(){
+      var utxo;
+      beforeEach(function(){
+        utxo = cloneObject(expectedUtxo)
+      })
+
+      it('uses hashLittleEndian when hash is not present', function(){
+        delete utxo[0]['hash']
+
+        wallet.setUnspentOutputs(utxo)
+        verifyOutputs()
+      })
+
+      it('uses hash when hashLittleEndian is not present', function(){
+        delete utxo[0]['hashLittleEndian']
+
+        wallet.setUnspentOutputs(utxo)
+        verifyOutputs()
+      })
+
+      it('uses hash when both hash and hashLittleEndian are present', function(){
+        wallet.setUnspentOutputs(utxo)
+        verifyOutputs()
+      })
+
+      function verifyOutputs() {
+        var output = wallet.outputs[expectedOutputKey]
+        assert(output)
+        assert.equal(output.value, utxo[0].value)
+        assert.equal(output.address, utxo[0].address)
+        assert.equal(output.scriptPubKey, utxo[0].scriptPubKey)
+      }
+    })
   })
 
   function assertEqual(obj1, obj2){
@@ -181,4 +215,9 @@ describe('Wallet', function() {
   function assertNotEqual(obj1, obj2){
     assert.notEqual(obj1.toString(), obj2.toString())
   }
+
+  // quick and dirty: does not deal with functions on object
+  function cloneObject(obj){
+    return JSON.parse(JSON.stringify(obj))
+  }
 })