forked from wakiyamap/lnd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
fee_service.go
114 lines (88 loc) · 2.42 KB
/
fee_service.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
106
107
108
109
110
111
112
113
114
package lntest
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"testing"
"github.com/monasuite/lnd/lnwallet/chainfee"
)
const (
// feeServiceTarget is the confirmation target for which a fee estimate
// is returned. Requests for higher confirmation targets will fall back
// to this.
feeServiceTarget = 1
)
// feeService runs a web service that provides fee estimation information.
type feeService struct {
feeEstimates
t *testing.T
srv *http.Server
wg sync.WaitGroup
url string
lock sync.Mutex
}
// feeEstimates contains the current fee estimates.
type feeEstimates struct {
Fees map[uint32]uint32 `json:"fee_by_block_target"`
}
// startFeeService spins up a go-routine to serve fee estimates.
func startFeeService(t *testing.T) *feeService {
port := NextAvailablePort()
f := feeService{
t: t,
url: fmt.Sprintf("http://localhost:%v/fee-estimates.json", port),
}
// Initialize default fee estimate.
f.Fees = map[uint32]uint32{feeServiceTarget: 50000}
listenAddr := fmt.Sprintf(":%v", port)
mux := http.NewServeMux()
mux.HandleFunc("/fee-estimates.json", f.handleRequest)
f.srv = &http.Server{
Addr: listenAddr,
Handler: mux,
}
f.wg.Add(1)
go func() {
defer f.wg.Done()
if err := f.srv.ListenAndServe(); err != http.ErrServerClosed {
f.t.Errorf("error: cannot start fee api: %v", err)
}
}()
return &f
}
// handleRequest handles a client request for fee estimates.
func (f *feeService) handleRequest(w http.ResponseWriter, r *http.Request) {
f.lock.Lock()
defer f.lock.Unlock()
bytes, err := json.Marshal(f.feeEstimates)
if err != nil {
f.t.Errorf("error: cannot serialize estimates: %v", err)
return
}
_, err = io.WriteString(w, string(bytes))
if err != nil {
f.t.Errorf("error: cannot send estimates: %v", err)
}
}
// stop stops the web server.
func (f *feeService) stop() {
if err := f.srv.Shutdown(context.Background()); err != nil {
f.t.Errorf("error: cannot stop fee api: %v", err)
}
f.wg.Wait()
}
// setFee changes the current fee estimate for the fixed confirmation target.
func (f *feeService) setFee(fee chainfee.SatPerKWeight) {
f.lock.Lock()
defer f.lock.Unlock()
f.Fees[feeServiceTarget] = uint32(fee.FeePerKVByte())
}
// setFeeWithConf sets a fee for the given confirmation target.
func (f *feeService) setFeeWithConf(fee chainfee.SatPerKWeight, conf uint32) {
f.lock.Lock()
defer f.lock.Unlock()
f.Fees[conf] = uint32(fee.FeePerKVByte())
}