Jelajahi Sumber

Update middleware.

Shomari 1 bulan lalu
induk
melakukan
0217bd5371

+ 71 - 88
web/handlers/buildSharedTx.ts

@@ -11,6 +11,8 @@ const bchjs = new BCHJS()
  * Build Shared Transaction
  *
  * Combine all participating inputs and outputs into one (signed) transaction.
+ *
+ * NOTE: ALL inputs are ALREADY signed by their respective participants.
  */
 export default function (_inputs, _outputs) {
     /* Initialize locals. */
@@ -18,82 +20,67 @@ export default function (_inputs, _outputs) {
     let safeBalance
     let utxo
 
-    try {
-        safeBalance = _inputs.reduce(
-            (acc, utxo) => (utxo.value >= 10000) ? acc + utxo.value : 0, 0
-        )
-        console.log('SAFE BALANCE', safeBalance)
-        const fee = bchjs.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 2 })
-        console.log('FEE', fee)
-
-        const paymentAmount = safeBalance - fee
-
-        const satsNeeded = fee + paymentAmount
-
-        const receiver = 'bitcoincash:qq27zfgmy7hckrrxygjdz6rr847pjkzzyc6d0un4e4'
-        console.log(`payment (+fee): ${satsNeeded}`)
-
-        const transactionBuilder = new bchjs.TransactionBuilder()
+    const transactionBuilder = new bchjs.TransactionBuilder()
 let inputIdx
-        this.fusionInputs.forEach((_utxo) => {
-            /* Set UTXO. */
-            utxo = _utxo
-            console.log('UTXO', utxo)
+    this.fusionInputs.forEach((_utxo) => {
+        /* Set UTXO. */
+        utxo = _utxo
+        console.log('UTXO', utxo)
 inputIdx = 0//utxo.tx_pos
-            transactionBuilder.addInput(utxo.tx_hash, utxo.tx_pos)
+        transactionBuilder.addInput(utxo.tx_hash, utxo.tx_pos)
 
-            const originalAmount = utxo.value
+        const originalAmount = utxo.value
 
-            const remainder = originalAmount - satsNeeded
-            console.log('REMAINDER', remainder);
+        const remainder = originalAmount - satsNeeded
+        console.log('REMAINDER', remainder);
 
-            if (remainder < 0) {
-                throw new Error('Selected UTXO does not have enough satoshis')
-            }
+        if (remainder < 0) {
+            throw new Error('Selected UTXO does not have enough satoshis')
+        }
 
 
-            const protocolId = '1337'
-            const msg = 'building...'
+        const protocolId = '1337'
+        const msg = 'building...'
 
-            const script = [
-                utf8ToBin(protocolId),
-                utf8ToBin(msg),
-            ]
-            console.log('my SCRIPT', script)
-            console.log('encodeNullData', encodeNullData(script))
+        const script = [
+            utf8ToBin(protocolId),
+            utf8ToBin(msg),
+        ]
+        console.log('my SCRIPT', script)
+        console.log('encodeNullData', encodeNullData(script))
 
-            // Compile the script array into a bitcoin-compliant hex encoded string.
-            // const data = bchjs.Script.encode(script)
-            const data = Buffer.from(encodeNullData(script))
-            console.log('OP_RETURN (data)', data)
+        // Compile the script array into a bitcoin-compliant hex encoded string.
+        // const data = bchjs.Script.encode(script)
+        const data = Buffer.from(encodeNullData(script))
+        console.log('OP_RETURN (data)', data)
 
-            // Add the OP_RETURN output.
-            // transactionBuilder.addOutput(data, 0)
-            transactionBuilder.addOutput(data, 0)
+        // Add the OP_RETURN output.
+        // transactionBuilder.addOutput(data, 0)
+        transactionBuilder.addOutput(data, 0)
 
 
 
-            // Send payment
-            // transactionBuilder.addOutput(receiver, satsNeeded)
-            transactionBuilder.addOutput(receiver, paymentAmount)
+        // Send payment
+        // transactionBuilder.addOutput(receiver, satsNeeded)
+        transactionBuilder.addOutput(receiver, paymentAmount)
 
-            // Send the BCH change back to the payment part
-            // transactionBuilder.addOutput(account.address, remainder - 300)
-        })
+        // Send the BCH change back to the payment part
+        // transactionBuilder.addOutput(account.address, remainder - 300)
+    })
 
-        /* Initialize redeem script. */
-        // FIXME Why do we need this??
-        let redeemScript
+    /* Initialize redeem script. */
+    // FIXME Why do we need this??
+    let redeemScript
 
-        /* Convert mnemonic to seed. */
-        const seed = mnemonicToSeed(this.mnemonic)
+    /* Convert mnemonic to seed. */
+    const seed = mnemonicToSeed(this.mnemonic)
 
-        /* Conver to seed buffer. */
-        // FIXME Migrate to TypedArrays.
-        const seedBuffer = Buffer.from(seed, 'hex')
+    /* Conver to seed buffer. */
+    // FIXME Migrate to TypedArrays.
+    const seedBuffer = Buffer.from(seed, 'hex')
 
-        /* Generate master node. */
-        const masterNode = bchjs.HDNode.fromSeed(seedBuffer)
+    /* Generate master node. */
+    const masterNode = bchjs.HDNode.fromSeed(seedBuffer)
 
 /* Set account index. */
 const accountIdx = 0
@@ -102,36 +89,32 @@ const changeIdx = 0
 /* Set address index. */
 const addressIdx = 0
 
-        /* Generate child node. */
-        const chidleNode = masterNode
-            .derivePath(`m/44'/145'/${accountIdx}'/${changeIdx}/${addressIdx}`)
-
-        /* Generate wallet import format (WIF). */
-        const wif = bchjs.HDNode.toWIF(chidleNode)
-        // console.log('BCH WIF', wif)
-
-        /* Generate elliptic pair. */
-        const ecPair = bchjs.ECPair.fromWIF(wif)
-
-        /* Sign transaction. */
-        transactionBuilder.sign(
-            inputIdx,
-            ecPair,
-            redeemScript,
-            Transaction.SIGHASH_ALL,
-            utxo.value,
-        )
-
-        /* Generate (incomplete) transaction. */
-        const tx = transactionBuilder.transaction.buildIncomplete()
-        // console.log('TRANSACTION', tx)
-
-        /* Convert to (raw) hex. */
-        rawTx = tx.toHex()
-    } catch (err) {
-        console.error(`Error in buildUnsignedTx(): ${err}`)
-        throw err
-    }
+    /* Generate child node. */
+    const chidleNode = masterNode
+        .derivePath(`m/44'/145'/${accountIdx}'/${changeIdx}/${addressIdx}`)
+
+    /* Generate wallet import format (WIF). */
+    const wif = bchjs.HDNode.toWIF(chidleNode)
+    // console.log('BCH WIF', wif)
+
+    /* Generate elliptic pair. */
+    const ecPair = bchjs.ECPair.fromWIF(wif)
+
+    /* Sign transaction. */
+    transactionBuilder.sign(
+        inputIdx,
+        ecPair,
+        redeemScript,
+        Transaction.SIGHASH_ALL,
+        utxo.value,
+    )
+
+    /* Generate (incomplete) transaction. */
+    const tx = transactionBuilder.transaction.buildIncomplete()
+    // console.log('TRANSACTION', tx)
+
+    /* Convert to (raw) hex. */
+    rawTx = tx.toHex()
 
     /* Return raw (hex) transaction. */
     return rawTx

+ 7 - 31
web/server/middleware/03-wallet.ts

@@ -26,30 +26,6 @@ let wallet
 /* Set constants. */
 const CHECK_FUSIONS_INTERVAL = 5000
 
-const sendTx = async (_tx) => {
-    const transactionBuilder = Bitcoin.TransactionBuilder
-        .fromTransaction(_tx, 'mainnet')
-    // const transactionBuilder = new bchjs.TransactionBuilder()
-    // console.log('TRANSACTION BUILDER', transactionBuilder)
-
-    // build tx
-    const tx = transactionBuilder.build()
-    // console.log('TRANSACTION BUILD', tx)
-
-    // output rawhex
-    const txHex = tx.toHex()
-
-    const finalTx = await bchjs.RawTransactions
-        .decodeRawTransaction(txHex)
-    console.log(`finalTx: ${JSON.stringify(finalTx, null, 2)}`)
-
-    // Broadcast transaction to the network
-    const txidStr = await bchjs.RawTransactions.sendRawTransaction(txHex)
-    console.log(`Exchange Tx ID: ${txidStr}`)
-    console.log(`https://explorer.bitcoinunlimited.info/tx/${txidStr}`)
-    console.log(`https://3xpl.com/bitcoin-cash/transaction/${txidStr}`)
-}
-
 /**
  * Initialize (Wallet)
  *
@@ -59,7 +35,7 @@ const init = async () => {
     wallet = await Wallet.init()
         .catch(err => console.error(err))
     // console.log('WALLET INIT', wallet)
-
+return // FIXME ONLY CLIENTS CAN BROADCAST FUSIONS
     let lastUpdate = 0
     let lastSnapshot
 
@@ -104,12 +80,13 @@ const init = async () => {
                     lastUpdate = _recent.updatedAt
                 }
 
-                if (_recent.rawTx) {
-                    let decoded = Bitcoin.Transaction.fromBuffer(Buffer.from(_recent.rawTx, 'hex'))
-                    console.log('DECODED RAW HEX', decoded)
+                /* Validate fusion progress. */
+                if (_recent.progress === 100.0) {
+                    /* Build transaction. */
+                    // rawTx = ...
 
-                    /* Send a transaction. */
-                    sendTx(decoded)
+                    /* Add to database. */
+                    // fusionsDb.rawTx
                 }
             })
             console.log('NEW LAST UPDATE', lastUpdate)
@@ -122,7 +99,6 @@ init()
 export default defineEventHandler((event) => {
     /* Set database. */
     const Db = event.context.Db
-    // console.log('DB', Db)
 
     /* Set fusions database. */
     fusionsDb = Db.fusions

+ 80 - 0
web/server/middleware/04-fusions.ts

@@ -0,0 +1,80 @@
+/* Import modules. */
+
+/* Initialize globals. */
+let fusionsDb
+
+/* Set constants. */
+const CHECK_FUSIONS_INTERVAL = 5000
+
+/**
+ * Initialize (Fusions)
+ *
+ * Setup a Fusions (background) handler.
+ */
+const init = async () => {
+        /* Manage Fusions */
+    setInterval(() => {
+        // console.log('Looking for DB(fusions) changes...', fusionsDb)
+
+        /* Set Fusion snapshot. */
+        const snapshot = JSON.stringify(fusionsDb)
+        // console.log('SNAPSHOT', snapshot)
+
+        /* Validate Fusion snapshot. */
+        if (fusionsDb && snapshot !== lastSnapshot) {
+            lastSnapshot = snapshot
+
+            /* Initialize recents. */
+            const recents = []
+
+            /* Handle fusions. */
+            Object.keys(fusionsDb).forEach(_fusionid => {
+                /* Set fusion. */
+                const fusion = fusionsDb[_fusionid]
+
+                /* Validate last update. */
+                if (typeof fusion.completedAt === 'undefined' && fusion.updatedAt > lastUpdate) {
+                    /* Add fusion. */
+                    recents.push(fusion)
+                }
+            })
+
+            console.log('RECENTS', lastUpdate, recents)
+
+            /* Handle recents. */
+            // NOTE: Update last update handler.
+            recents.forEach(_recent => {
+                if (_recent.updatedAt > lastUpdate) {
+                    /* Set (new) last update. */
+                    lastUpdate = _recent.updatedAt
+                }
+
+                /* Validate fusion progress. */
+                if (_recent.progress === 100.0) {
+                    /* Build transaction. */
+                    // rawTx = ...
+
+// console.log('FOUND CHANGES??', snapshot)
+// txObj.ins[1].script = txObj2.ins[1].script
+// txObj.ins[2].script = txObj3.ins[2].script
+
+                    /* Add to database. */
+                    // fusionsDb.rawTx
+                }
+            })
+            console.log('NEW LAST UPDATE', lastUpdate)
+        }
+    }, CHECK_FUSIONS_INTERVAL)
+}
+// init()
+
+export default defineEventHandler((event) => {
+    /* Set database. */
+    const Db = event.context.Db
+
+    /* Set fusions database. */
+    fusionsDb = Db.fusions
+
+    /* Inject wallet into server context. */
+    event.context.Wallet = wallet
+})