// Collaborative offboard — move whole VTXOs back to an on-chain output with // the server's cooperation. Two RPCs: PrepareOffboard (server builds the // on-chain tx and sends forfeit cosign nonces) and FinishOffboard (we // countersign a musig forfeit per input; server returns the fully-signed tx // for us to broadcast). Mirrors bark lib/src/offboard.rs. // // The fee math must match the server BIT FOR BIT: captaind recomputes the fee // and rejects the request unless net_amount == gross - fee exactly // (server/src/offboards.rs). Rounding mirrors rust-bitcoin 0.32 + bark: // weight fee rounds up ((rate*wu + 999) / 1000), ppm fees round down. import { hex } from '@scure/base'; import { sha256 } from '@noble/hashes/sha256'; import { schnorr, secp256k1 } from '@noble/curves/secp256k1'; import * as musig2 from '@scure/btc-signer/musig2'; import { concatBytes, grpcCall, pbWriter, pbFields } from './proto.js'; import { P2A_SCRIPT, pubkeyPolicyTaproot, taprootSighash, txid } from './send.js'; const te = new TextEncoder(); export const P2TR_DUST = 330; const OFFBOARD_VOUT = 0; const CONNECTOR_VOUT = 1; const u32le = (n) => Uint8Array.of(n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >>> 24) & 0xff); const u64le = (n) => { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, BigInt(n), true); return b; }; const varint = (n) => { if (n < 0xfd) return Uint8Array.of(n); throw new Error('script longer than 252 bytes not supported'); }; const taggedHash = (tag, ...data) => { const th = sha256(te.encode(tag)); return sha256(concatBytes(th, th, ...data)); }; // ScriptBuf::new_p2tr(key, None): x-only key tweaked by H_TapTweak(key), no // script tree — the forfeit tx pays the server this way. export function bareP2tr(pub33) { const x = pub33.slice(1); const tweak = taggedHash('TapTweak', x); const P = secp256k1.ProjectivePoint; const out = P.fromHex(concatBytes(Uint8Array.of(0x02), x)) .add(P.BASE.multiply(BigInt('0x' + hex.encode(tweak)))); return concatBytes(hex.decode('5120'), out.toRawBytes(true).slice(1)); } // Current offboard fee rate in sat/kvB. export async function getOffboardFeeRate(ark) { const data = await grpcCall(ark, 'bark_server.ArkService/GetOffboardFeeRate', new Uint8Array(0)); for (const { field, value } of pbFields(data)) if (field === 1) return Number(value); return 0; } // bark: FeeRate::from_sat_per_kwu(sat_vkb / 4) export const feeRateKwu = (satVkb) => Math.floor(satVkb / 4); // OffboardFees::calculate — base + ceil(rate * weight) + per-vtxo ppm-by-expiry. // inputs: [{ amountSat, expiryHeight }]; fees: info.offboardFees. export function offboardFee({ spkLen, satVkb, fees, tip, inputs }) { const wu = (fees.fixedAdditionalVb + spkLen) * 4; const weightFee = Math.floor((feeRateKwu(satVkb) * wu + 999) / 1000); // pver >= 4: sub-satoshi ppm accumulates across vtxos, one round-up at the end let ppmUnits = 0; for (const v of inputs) { const blocks = Math.max(0, v.expiryHeight - tip); const entry = [...fees.ppmExpiryTable].reverse().find((e) => blocks >= e.thresholdBlocks); if (entry) ppmUnits += v.amountSat * entry.ppm; } return fees.baseFeeSat + weightFee + Math.ceil(ppmUnits / 1_000_000); } // OffboardRequestAttestation: BIP340 signature over // sha256(prefix32 || txout(net, spk) || u32le(n) || vtxo ids), per input key. const OFFBOARD_ATT_PREFIX = te.encode('Ark offboard request challenge '); // 32 bytes export function offboardAttestation({ netSat, spk, inputIdRaws }, privkey) { const msg = sha256(concatBytes( OFFBOARD_ATT_PREFIX, u64le(netSat), varint(spk.length), spk, u32le(inputIdRaws.length), ...inputIdRaws, )); return schnorr.sign(msg, privkey); } export async function prepareOffboard(ark, { netSat, spk, rateKwu, inputIdRaws, attestations }) { const req = pbWriter(); req.varintField(1, netSat); req.bytesField(2, spk); req.varintField(3, 1); // deduct_fees_from_gross_amount req.varintField(5, rateKwu); const w = pbWriter(); w.bytesField(1, req.finish()); for (const id of inputIdRaws) w.bytesField(2, id); for (const a of attestations) w.bytesField(3, a); const data = await grpcCall(ark, 'bark_server.ArkService/PrepareOffboard', w.finish()); let txBytes = null; const serverNonces = []; for (const { field, value } of pbFields(data)) { if (field === 1) txBytes = value; if (field === 2) serverNonces.push(value); } if (!txBytes || serverNonces.length !== inputIdRaws.length) { throw new Error('malformed PrepareOffboard response'); } return { txBytes, serverNonces }; } // The user-side checks from OffboardForfeitContext::validate_offboard_tx. export function validateOffboardTx(parsed, { netSat, spk, nInputs }) { const out = parsed.outputs[OFFBOARD_VOUT]; if (!out || out.valueSat !== netSat || hex.encode(out.scriptPubKey) !== hex.encode(spk)) { throw new Error('offboard tx output does not match request'); } const conn = parsed.outputs[CONNECTOR_VOUT]; if (!conn || conn.valueSat !== P2TR_DUST * nInputs) { throw new Error('offboard tx has insufficient connector value'); } } // Sign one forfeit per input. Each forfeit spends [vtxo, connector] and pays // vtxo.amount + dust to the server's bare key. With >1 input the connectors // come from a deterministic fanout tx that splits the offboard tx's single // connector output into one dust output per input. export function signOffboardForfeits({ inputs, keys, serverPub, parsed, serverNonces }) { const offTxidInternal = hex.decode(parsed.txid).reverse(); const connSpk = parsed.outputs[CONNECTOR_VOUT].scriptPubKey; const outpoint = (txidInt, vout) => concatBytes(txidInt, u32le(vout)); let connectors; if (inputs.length === 1) { connectors = [{ raw: outpoint(offTxidInternal, CONNECTOR_VOUT), txout: parsed.outputs[CONNECTOR_VOUT] }]; } else { const fanout = { version: 3, locktime: 0, inputs: [{ prevout: outpoint(offTxidInternal, CONNECTOR_VOUT), sequence: 0xffffffff }], outputs: [ ...inputs.map(() => ({ valueSat: P2TR_DUST, scriptPubKey: connSpk })), { valueSat: 0, scriptPubKey: P2A_SCRIPT }, ], }; const fanTxid = txid(fanout); // The forfeits spend the fanout's outputs (one dust each) — the sighash // commits to prevout values, so it must be the per-output dust, not the // combined connector sum. connectors = inputs.map((_, i) => ({ raw: outpoint(fanTxid, i), txout: { valueSat: P2TR_DUST, scriptPubKey: connSpk }, })); } const pubNonces = []; const partials = []; inputs.forEach((input, i) => { const k = keys[i]; const tap = pubkeyPolicyTaproot(k.pubkey, serverPub, input.exitDelta); const forfeitTx = { version: 3, locktime: 0, inputs: [ { prevout: input.point.raw, sequence: 0xffffffff }, { prevout: connectors[i].raw, sequence: 0xffffffff }, ], outputs: [ { valueSat: input.amountSat + P2TR_DUST, scriptPubKey: bareP2tr(serverPub) }, { valueSat: 0, scriptPubKey: P2A_SCRIPT }, ], }; const prevouts = [ { valueSat: input.amountSat, scriptPubKey: tap.scriptPubKey }, connectors[i].txout, ]; const sighash = taprootSighash(forfeitTx, prevouts); const nonces = musig2.nonceGen(k.pubkey, k.privkey, undefined, sighash); const aggNonce = musig2.nonceAggregate([nonces.public, serverNonces[i]]); const session = new musig2.Session(aggNonce, tap.sortedKeys, sighash, [tap.tapTweak], [true]); partials.push(session.sign(nonces.secret, k.privkey)); pubNonces.push(nonces.public); }); return { pubNonces, partials, offboardTxidInternal: offTxidInternal }; } export async function finishOffboard(ark, { offboardTxidInternal, pubNonces, partials }) { const w = pbWriter(); w.bytesField(1, offboardTxidInternal); for (const n of pubNonces) w.bytesField(2, n); for (const p of partials) w.bytesField(3, p); const data = await grpcCall(ark, 'bark_server.ArkService/FinishOffboard', w.finish()); for (const { field, value } of pbFields(data)) if (field === 1) return value; throw new Error('no signed offboard tx in response'); } 103'>103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
moment = require('moment')
EXCHANGE_FAIL = "Problem fetching exchange rate"
SOCKET_FAIL = "Problem connecting to payment server, notifications may not appear"
ADDRESS_FAIL = "Invalid address"
g = exports ? this
g.errors = []
g.amount_requested = 0
g.amount = 0.toFixed(2)
g.tip = 1
g.transactions = []
$(->
$.ajax(
url: $('#user').val() + '.json',
dataType: 'json',
success: (data) ->
g.user = data
setup()
)
$('button').click((e) ->
e.preventDefault()
)
$('.numpad .btn').off('click').click((e) ->
e.preventDefault()
m = $(this).html()
n = parseFloat($('.amount').html())
if m is 'C'
g.amount = 0.toFixed(2)
updateTotal()
return
return if n > 1000
if m is '00'
n = 100 * n
else
n = 10 * n + parseFloat(m) / 100
g.amount = n.toFixed(2)
updateTotal()
)
$('.numpad .btn:last').off('click').click((e) ->
e.preventDefault()
g.amount = (Math.floor(100 * (parseFloat($('.amount').html()) / 10)) / 100).toFixed(2)
updateTotal()
)
$('.tippad .btn').off('click').click((e) ->
e.preventDefault()
$(this).addClass('active')
value = $(this).html().slice(0, -1)
$(this).siblings().css('font-weight','normal').removeClass('active')
$(this).css('font-weight','bold')
g.tip = 1 + (parseFloat(value)/100)
updateTotal()
)
$('#received').click(-> window.location = "/#{g.user.username}/report")
$('#slide').click(->
$('#controls').slideToggle()
$(this).find('i').toggleClass('fa-sort-up').toggleClass('fa-sort-down')
)
)
setup = ->
g.user.address or= ''
g.user.commission or= 0
g.user.currency or= 'CAD'
g.user.symbol or= 'quadrigacx'
g.user.unit or= 'BTC'
if g.user.title
$('#title').html("<a href='/#{g.user.username}/edit'>#{g.user.title}</a>").show()
if g.user.logo
ext = g.user.logo.substr(g.user.logo.length - 3)
src = "/img/logos/#{g.user.username}.#{ext}"
$('#logo').attr('src', src).show()
getAddress()
$('.symbol').html(g.user.currency)
$('.currency').html(g.user.currency)
$('.unit').html(g.user.unit)
$('#received').hide()
fetchExchangeRate()
listen()
fetchExchangeRate = ->
$.ajax(
url: "ticker?currency=#{g.user.currency}&symbol=#{g.user.symbol}&type=bid",
success: (exchange) ->
if exchange?
clear(EXCHANGE_FAIL)
else
fail(EXCHANGE_FAIL)
return
g.exchange = (exchange - exchange * g.user.commission * 0.01).toFixed(2)
$('#exchange').html(g.exchange)
updateTotal()
unless g.setupComplete
g.setupComplete = true
error: -> fail(EXCHANGE_FAIL)
)
setTimeout(fetchExchangeRate, 900000)
updateTotal = ->
precision = 9 - multiplier().toString().length
subtotal = parseFloat(g.amount * g.tip).toFixed(2)
total = (subtotal * multiplier() / g.exchange).toFixed(precision)
g.amount_requested = (subtotal / g.exchange).toFixed(8)
unless $.isNumeric(total)
total = ''
$('#received').hide()
$('#payment').fadeIn('slow')
$('.tip').html((subtotal - g.amount).toFixed(2))
$('.subtotal').html(subtotal.toString())
$('.amount').html(g.amount)
$('.exchange').html(g.exchange)
$('.symbol').html(g.user.symbol)
if g.user.commission < 0
$('.commission').html("+#{Math.abs(g.user.commission)}%")
$('#total').html(total.toString())
$('#qr').html('')
# size = $('#calculator').width() * 0.7
size = 300
$('#qr').css('height', size)
new QRCode('qr',
text: "bitcoin:#{g.user.address}?amount=#{g.amount_requested.toString()}"
width: size
height: size
)
listen = ->
g.attempts++
if g.blockchain and g.blockchain.readyState is 1
setTimeout(listen, 12000)
else
fail(SOCKET_FAIL) if g.attempts > 3
g.blockchain = new WebSocket("wss://ws.blockchain.info/inv")
g.blockchain.onopen = ->
if g.blockchain.readyState is 1
g.attempts = 0
clear(SOCKET_FAIL)
g.blockchain.send('{"op":"addr_sub", "addr":"' + g.user.address + '"}')
else
setTimeout(g.blockchain.onopen, 12000 * g.attempts)
g.blockchain.onerror = ->
fail(SOCKET_FAIL)
g.blockchain.close()
delete g.blockchain
listen()
g.blockchain.onclose = ->
delete g.blockchain
listen()
g.blockchain.onmessage = (e) ->
results = eval('(' + e.data + ')')
amount = 0
txid = results.x.hash
return if txid == g.last
g.last = txid
$.each(results.x.out, (i, v) ->
if (v.addr == g.user.address)
amount += v.value / 100000000
)
logTransaction(txid, amount)
logTransaction = (txid, amount) ->
if $('#received').is(":hidden") and amount >= g.amount_requested
$('#payment').hide()
$('#received').fadeIn('slow')
$('#success')[0].play()
g.user.index++
if g.transactions.indexOf(txid) is -1
g.transactions.push(txid)
$.post("/#{g.user.username}/transactions",
txid: txid,
address: g.user.address,
date: moment().format("YYYY-MM-DD HH:mm:ss"),
received: amount,
exchange: g.exchange
)
getAddress()
getAddress = ->
try
bitcoin.address.fromBase58Check(g.user.pubkey)
g.user.address = g.user.pubkey
catch
try
master = bitcoin.HDNode.fromBase58(g.user.pubkey)
child = master.derive(0).derive(g.user.index)
g.user.address = child.getAddress().toString()
g.blockchain.close() if g.blockchain
listen()
catch
fail(ADDRESS_FAIL)
$('#address').html("<a href='https://tradeblock.com/bitcoin/address/#{g.user.address}'>#{g.user.address}</a>")
fail = (msg) ->
g.errors.push(msg)
g.errors = g.errors.uniq()
$('#error').show().html(g.errors.toString())
clear = (msg) ->
i = g.errors.indexOf(msg)
g.errors.splice(i, 1) if i >= 0
if (g.errors.length > 0)
$('#error').show().html(g.errors.toString())
else
$('#error').hide()
$('#calculator').fadeIn('slow')
Array::uniq = ->
output = {}
output[@[key]] = @[key] for key in [0...@length]
value for key, value of output
multiplier = ->
switch g.user.unit
when 'BTC' then 1
when 'mBTC' then 1000
when 'µBTC' then 1000000
when 'bits' then 1000000
when 'satoshis' then 100000000