This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 285
/
notify.go
76 lines (72 loc) · 2.06 KB
/
notify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package bitcoind
import (
"github.com/OpenBazaar/spvwallet"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcrpcclient"
"io/ioutil"
"net/http"
"time"
)
type NotificationListener struct {
client *btcrpcclient.Client
listeners []func(spvwallet.TransactionCallback)
}
func (l *NotificationListener) notify(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
txid := string(b)
hash, err := chainhash.NewHashFromStr(txid)
if err != nil {
log.Error(err)
return
}
tx, err := l.client.GetRawTransaction(hash)
if err != nil {
log.Error(err)
return
}
watchOnly := false
txInfo, err := l.client.GetTransaction(hash, &watchOnly)
if err != nil {
watchOnly = true
}
var outputs []spvwallet.TransactionOutput
for i, txout := range tx.MsgTx().TxOut {
out := spvwallet.TransactionOutput{ScriptPubKey: txout.PkScript, Value: txout.Value, Index: uint32(i)}
outputs = append(outputs, out)
}
var inputs []spvwallet.TransactionInput
for _, txin := range tx.MsgTx().TxIn {
in := spvwallet.TransactionInput{OutpointHash: txin.PreviousOutPoint.Hash.CloneBytes(), OutpointIndex: txin.PreviousOutPoint.Index}
prev, err := l.client.GetRawTransaction(&txin.PreviousOutPoint.Hash)
if err != nil {
inputs = append(inputs, in)
continue
}
in.LinkedScriptPubKey = prev.MsgTx().TxOut[txin.PreviousOutPoint.Index].PkScript
in.Value = prev.MsgTx().TxOut[txin.PreviousOutPoint.Index].Value
inputs = append(inputs, in)
}
cb := spvwallet.TransactionCallback{
Txid: tx.Hash().CloneBytes(),
Inputs: inputs,
Outputs: outputs,
WatchOnly: watchOnly,
Value: int64(txInfo.Amount * 100000000),
Timestamp: time.Unix(txInfo.TimeReceived, 0),
Height: int32(txInfo.BlockIndex),
}
for _, lis := range l.listeners {
lis(cb)
}
}
func startNotificationListener(client *btcrpcclient.Client, listeners []func(spvwallet.TransactionCallback)) {
l := NotificationListener{
client: client,
listeners: listeners,
}
http.HandleFunc("/", l.notify)
http.ListenAndServe(":8330", nil)
}