forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notify.go
105 lines (100 loc) · 2.61 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package bitcoind
import (
"encoding/json"
"github.com/OpenBazaar/wallet-interface"
"github.com/btcsuite/btcd/chaincfg/chainhash"
btcrpcclient "github.com/btcsuite/btcd/rpcclient"
"io/ioutil"
"net/http"
"time"
)
type NotificationListener struct {
client *btcrpcclient.Client
listeners []func(wallet.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 []wallet.TransactionOutput
for i, txout := range tx.MsgTx().TxOut {
out := wallet.TransactionOutput{ScriptPubKey: txout.PkScript, Value: txout.Value, Index: uint32(i)}
outputs = append(outputs, out)
}
var inputs []wallet.TransactionInput
for _, txin := range tx.MsgTx().TxIn {
in := wallet.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)
}
height := int32(0)
if txInfo.Confirmations > 0 {
hash, err := chainhash.NewHashFromStr(txInfo.BlockHash)
if err != nil {
log.Error(err)
return
}
h := ``
if hash != nil {
h += `"` + hash.String() + `"`
}
resp, err := l.client.RawRequest("getblockheader", []json.RawMessage{json.RawMessage(h)})
if err != nil {
log.Error(err)
return
}
type Respose struct {
Height int32 `json:"height"`
}
r := new(Respose)
err = json.Unmarshal([]byte(resp), r)
if err != nil {
log.Error(err)
return
}
height = r.Height
}
cb := wallet.TransactionCallback{
Txid: tx.Hash().CloneBytes(),
Inputs: inputs,
Outputs: outputs,
WatchOnly: watchOnly,
Value: int64(txInfo.Amount * 100000000),
Timestamp: time.Unix(txInfo.TimeReceived, 0),
Height: height,
}
for _, lis := range l.listeners {
lis(cb)
}
}
func StartNotificationListener(client *btcrpcclient.Client, listeners []func(wallet.TransactionCallback)) {
l := NotificationListener{
client: client,
listeners: listeners,
}
http.HandleFunc("/", l.notify)
http.ListenAndServe(":8330", nil)
}