1 // Command btcd-lited is one instance: a data directory served over HTTP, a
2 // relay for its chains' client transactions, and optionally a fill from a peer
3 // over BIP324 and a seed from another instance's service.
4 //
5 // btcd-lited -chains btc,xbt -data ./data -listen 127.0.0.1:8080 \
6 // -peer btc=127.0.0.1:8333,xbt=127.0.0.1:8333
7 //
8 // One process holds both chains over one body store: the blocks the two chains
9 // share are stored once, and each chain's header store is the index that gives
10 // them heights. With -peer it syncs each chain's header chain over p2p and
11 // fills the body store from the same peer, over one connection per chain. With
12 // -relay it takes client transactions at POST /v1/chains/{chain}/tx and
13 // announces them to the peers it is given for that purpose. The HTTP service is
14 // a view of the data directory and does not depend on either.
15 package main
16 17 import (
18 "context"
19 "crypto/ed25519"
20 "encoding/hex"
21 "encoding/json"
22 "flag"
23 "fmt"
24 "log"
25 "net/http"
26 "os"
27 "os/signal"
28 "path/filepath"
29 "runtime"
30 "strings"
31 "syscall"
32 "time"
33 34 "git.smesh.lol/btcd-lite/internal/chains"
35 "git.smesh.lol/btcd-lite/internal/filler"
36 "git.smesh.lol/btcd-lite/internal/filterstore"
37 "git.smesh.lol/btcd-lite/internal/filtersync"
38 "git.smesh.lol/btcd-lite/internal/litedial"
39 "git.smesh.lol/btcd-lite/internal/logging"
40 "git.smesh.lol/btcd-lite/internal/process"
41 "git.smesh.lol/btcd-lite/internal/relay"
42 "git.smesh.lol/btcd-lite/internal/serve"
43 "git.smesh.lol/btcd-lite/internal/service"
44 "git.smesh.lol/btcd-lite/internal/staging"
45 "git.smesh.lol/btcd-lite/internal/store"
46 utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve"
47 "git.smesh.lol/btcd-lite/internal/v2peer"
48 "git.smesh.lol/nostrino/pkg/btcwire"
49 "git.smesh.lol/nostrino/pkg/neutrino"
50 )
51 52 func main() {
53 chainList := flag.String("chains", chains.Parent+","+chains.Fork, "comma-separated chains to hold: btc, xbt")
54 chainName := flag.String("chain", "", "one chain to hold; an alias for a single-entry -chains")
55 data := flag.String("data", "", "instance data directory")
56 listen := flag.String("listen", "127.0.0.1:8080", "HTTP listen address")
57 peerList := flag.String("peer", "", "p2p peers to fill from, as chain=host:port entries")
58 relayList := flag.String("relay", "", "p2p peers to announce transactions to, as chain=host:port entries")
59 keyFile := flag.String("key", "", "Ed25519 seed file the published manifest is signed with")
60 regtest := flag.Bool("regtest", false, "use the local test chain's genesis and parameters")
61 processAfter := flag.Bool("process-after-fill", true, "process the staging log after a fill")
62 processOnly := flag.Bool("process-only", false, "process the staging log and serve, dialling no peers")
63 level := flag.String("log-level", "info", "debug, info, warn or error")
64 logFile := flag.String("log-file", "", "append the log to this file; empty means stderr")
65 heartbeat := flag.Duration("heartbeat", 5*time.Minute, "how often to write a status line; 0 disables it")
66 fillProgress := flag.Duration("fill-progress", time.Minute, "how often to write a fill progress line; 0 disables it")
67 useV2 := flag.Bool("v2", false, "use BIP324 (v2) transport; plaintext v1 is the default because the v2 path closes connections part way through a sync against some real peers")
68 // Off by default: a synced fold is anchored by whichever peer served it,
69 // because the block headers do not commit to the filter chain. The dataset
70 // builder computes filters from bodies instead, which needs no peer.
71 verifyStore := flag.Bool("verify-store", true, "read every stored block back when opening the store; false opens on the index alone and is what a dataset too big to scan needs")
72 doFilters := flag.Bool("filters", false, "sync the BIP157 filter chain from the peer instead of computing it")
73 filtersOnly := flag.Bool("filters-only", false, "sync filters and stop; no block fill")
74 flag.Parse()
75 if *chainName != "" {
76 *chainList = *chainName
77 }
78 names, err := chainListOf(*chainList)
79 if err != nil {
80 fmt.Fprintf(os.Stderr, "btcd-lited: %v\n", err)
81 os.Exit(2)
82 }
83 peers, err := peersOf(*peerList, names)
84 if err != nil {
85 fmt.Fprintf(os.Stderr, "btcd-lited: -peer: %v\n", err)
86 os.Exit(2)
87 }
88 relayPeers, err := peersOf(*relayList, names)
89 if err != nil {
90 fmt.Fprintf(os.Stderr, "btcd-lited: -relay: %v\n", err)
91 os.Exit(2)
92 }
93 if *data == "" {
94 fmt.Fprintln(os.Stderr, "btcd-lited: -data is required")
95 os.Exit(2)
96 }
97 lvl, err := logging.ParseLevel(*level)
98 if err != nil {
99 fmt.Fprintln(os.Stderr, "btcd-lited: -log-level:", err)
100 os.Exit(2)
101 }
102 lg, err := logging.OpenFile(*logFile, lvl)
103 if err != nil {
104 fmt.Fprintln(os.Stderr, "btcd-lited:", err)
105 os.Exit(2)
106 }
107 defer lg.Close()
108 // What the process was asked to do, before it does any of it. A run that
109 // leaves no trace of its own arguments is a run that cannot be told apart
110 // from one that never started.
111 startup := map[string]any{
112 "version": "btcd-lited", "chains": names, "data": *data, "listen": *listen,
113 "peers": peers, "relay_peers": relayPeers, "key": *keyFile != "", "regtest": *regtest,
114 "process_after_fill": *processAfter, "process_only": *processOnly,
115 "log_level": lvl.String(), "heartbeat": heartbeat.String(),
116 }
117 if raw, err := json.Marshal(startup); err == nil {
118 lg.Infof("start %s", raw)
119 }
120 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
121 defer stop()
122 if os.Getenv("BTCD_LITE_TRACE") != "" {
123 v2peer.SetTrace(func(f string, a ...any) { log.Printf(f, a...) })
124 }
125 cfg := instanceConfig{
126 chains: names, data: *data, listen: *listen,
127 peers: peers, relayPeers: relayPeers,
128 keyFile: *keyFile, regtest: *regtest,
129 processAfter: *processAfter, processOnly: *processOnly,
130 log: lg, heartbeat: *heartbeat, fillProgress: *fillProgress, v2: *useV2,
131 filters: *doFilters, filtersOnly: *filtersOnly, verifyStore: *verifyStore,
132 }
133 lg.ReopenOnHangup()
134 lg.SignalLevels(lvl)
135 if err := run(ctx, cfg); err != nil {
136 lg.Errorf("%v", err)
137 os.Exit(1)
138 }
139 }
140 141 type instanceConfig struct {
142 chains []string
143 data, listen string
144 peers, relayPeers map[string][]string
145 keyFile string
146 regtest bool
147 processAfter bool
148 processOnly bool
149 log *logging.Logger
150 heartbeat time.Duration
151 fillProgress time.Duration
152 v2 bool
153 verifyStore bool
154 filters bool
155 filtersOnly bool
156 }
157 158 func run(ctx context.Context, c instanceConfig) error {
159 lg := c.log
160 info := make(map[string]chains.Chain, len(c.chains))
161 for _, name := range c.chains {
162 ci, err := chains.ByName(name)
163 if err != nil {
164 return err
165 }
166 if c.regtest {
167 ci = chains.Regtest()
168 ci.Name = name
169 }
170 info[name] = ci
171 }
172 // The fill connections are dialed before any store is opened. This is the
173 // one variable left in a disagreement that cost many rounds: the same
174 // dialler and the same arguments completed in thirteen milliseconds from a
175 // test binary and stalled for the node's whole handshake timeout when the
176 // instance called it after opening its stores. Dialing first removes the
177 // variable; if the instance still stalls, the difference is not in what
178 // runs before the dial.
179 conns := make(map[string]*v2peer.Peer, len(c.chains))
180 connAddr := make(map[string]string, len(c.chains))
181 for _, name := range c.chains {
182 if c.processOnly {
183 break
184 }
185 // The header chain comes from the first peer that answers with the
186 // service this instance needs, and every configured address is tried
187 // before the fill is given up on: a peer that accepts TCP and then does
188 // not speak has to fail without stopping the chain.
189 var fallback *v2peer.Peer
190 var fallbackAddr string
191 for _, addr := range c.peers[name] {
192 lg.Infof("fill %s: dialling %s", name, addr)
193 // Twenty seconds for the handshake, not two minutes: a peer that
194 // accepts TCP and then says nothing is one of eight, and the walk
195 // has to get past it to the one that answers.
196 peer, err := litedial.Connect(ctx, addr, "/btcd-lite:0.1.0/",
197 info[name].WireMagic(), 20*time.Second, c.v2, lg.Logf)
198 if err != nil {
199 lg.Errorf("fill %s: %s: %v", name, addr, err)
200 continue
201 }
202 // A peer that serves compact filters is preferred for the header
203 // chain, because the filter sync runs over this connection and a
204 // node that does not advertise the service disconnects a peer that
205 // asks. The first peer that answers is kept as a fallback.
206 if peer.Services()&nodeCompactFilters != 0 {
207 if fallback != nil {
208 _ = fallback.Close()
209 }
210 conns[name], connAddr[name] = peer, addr
211 lg.Infof("fill %s: %s serves compact filters", name, addr)
212 break
213 }
214 if fallback == nil {
215 fallback, fallbackAddr = peer, addr
216 lg.Infof("fill %s: %s does not serve compact filters, looking for one that does", name, addr)
217 continue
218 }
219 _ = peer.Close()
220 }
221 if _, ok := conns[name]; !ok && fallback != nil {
222 conns[name], connAddr[name] = fallback, fallbackAddr
223 }
224 }
225 bodies, err := openBodies(c.data, c.verifyStore)
226 if err != nil {
227 return fmt.Errorf("blocks: %w", err)
228 }
229 defer bodies.Close()
230 headers := make(map[string]*store.HeaderStore, len(c.chains))
231 view := serve.New(headers, bodies)
232 for _, name := range c.chains {
233 hs, err := store.NewHeaderStore(filepath.Join(c.data, "headers", name))
234 if err != nil {
235 return fmt.Errorf("headers %s: %w", name, err)
236 }
237 defer hs.Close()
238 headers[name] = hs
239 genesis, err := info[name].Genesis()
240 if err != nil {
241 return err
242 }
243 if _, _, ok := hs.HeaderTip(); !ok {
244 // A fresh store starts at the chain's genesis, which is the one
245 // header a peer's first answer links to.
246 if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis.BlockHash(), FilterHeight: -1}); err != nil {
247 return fmt.Errorf("anchor %s: %w", name, err)
248 }
249 if err := hs.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil {
250 return fmt.Errorf("seed genesis %s: %w", name, err)
251 }
252 }
253 }
254 if c.keyFile != "" {
255 key, err := readKey(c.keyFile)
256 if err != nil {
257 return err
258 }
259 view.Key = key
260 }
261 262 filters, err := filterstore.Open(filterstore.Dir(c.data))
263 if err != nil {
264 return fmt.Errorf("filters: %w", err)
265 }
266 defer filters.Close()
267 staged := make(map[string]*staging.Log, len(c.chains))
268 for _, name := range c.chains {
269 l, err := staging.Open(staging.Dir(c.data, name))
270 if err != nil {
271 return fmt.Errorf("staging %s: %w", name, err)
272 }
273 defer l.Close()
274 staged[name] = l
275 }
276 for _, name := range c.chains {
277 peer, ok := conns[name]
278 if !ok {
279 if len(c.peers[name]) > 0 {
280 lg.Warnf("fill %s: no connection to any of %d peers, serving what the data directory holds", name, len(c.peers[name]))
281 } else {
282 lg.Infof("fill %s: no peer given, serving what the data directory holds", name)
283 }
284 continue
285 }
286 if err := fill(ctx, info[name], headers[name], filters, bodies, staged[name], c.peers[name], connAddr[name], peer, lg, c.fillProgress, c.v2, c.filters, c.filtersOnly); err != nil && ctx.Err() == nil {
287 lg.Errorf("fill %s: %v", name, err)
288 }
289 }
290 if c.processAfter {
291 for _, name := range c.chains {
292 if err := runProcess(c.data, name, staged[name], headers[name], bodies, lg); err != nil {
293 lg.Errorf("process %s: %v", name, err)
294 }
295 }
296 }
297 298 handlers := map[string]*relay.Handler{}
299 for _, name := range c.chains {
300 addrs := c.relayPeers[name]
301 if len(addrs) == 0 {
302 continue
303 }
304 window := relay.NewWindow(128 << 20)
305 rel, err := relay.New(relay.RelayConfig{Profile: info[name].Profile, Window: window, Peers: addrs, V2: c.v2, Logf: lg.Logf})
306 if err != nil {
307 return err
308 }
309 go rel.Start(ctx)
310 go rel.Follow(ctx, headers[name], nil, 15*time.Second)
311 go rel.Rebroadcast(ctx, 45*time.Minute)
312 handlers[name] = &relay.Handler{Chain: name, Relay: rel, Window: window}
313 }
314 315 view.Filters = filters
316 mux := http.NewServeMux()
317 service.Routes(mux, view, service.WithUTXO(utxoSources(c.data, c.chains)))
318 for _, name := range c.chains {
319 sets, diffs := utxoDirs(c.data, name)
320 utxoserve.Routes(mux, utxoserve.Chain{Name: name, Sets: sets, Diffs: diffs, Interval: info[name].Exported.Retarget})
321 }
322 if len(handlers) > 0 {
323 relay.Multi(mux, handlers)
324 }
325 srv := &http.Server{
326 Addr: c.listen, Handler: lg.Handler(mux),
327 ReadHeaderTimeout: 10 * time.Second, WriteTimeout: 10 * time.Minute,
328 ErrorLog: log.New(lg.Writer(), "", log.LstdFlags),
329 }
330 go func() {
331 <-ctx.Done()
332 shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
333 defer cancel()
334 _ = srv.Shutdown(shutdown)
335 }()
336 lg.Infof("serving: chains=%s data=%s listen=%s blocks=%d filters=%d relays=%d",
337 strings.Join(c.chains, ","), c.data, c.listen, bodies.Len(), filters.Len(), len(handlers))
338 go lg.Heartbeat(ctx, c.heartbeat, func() string {
339 return report(lg, c.chains, headers, bodies, filters, staged)
340 })
341 if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
342 return err
343 }
344 return nil
345 }
346 347 // runProcess turns one chain's staging log into stored blocks.
348 func runProcess(data, name string, staged *staging.Log, headers *store.HeaderStore, bodies *store.BlockStore, lg *logging.Logger) error {
349 if staged.Len() == 0 {
350 lg.Infof("process %s: nothing staged", name)
351 return nil
352 }
353 res, err := process.Run(process.Config{
354 Chain: name, Staging: staged, Bodies: bodies, Headers: headers,
355 Missing: process.MissingName(data, name), Logf: lg.Logf,
356 })
357 if err != nil {
358 return err
359 }
360 if res.Dropped > 0 {
361 lg.Warnf("process %s: %d bodies refused, recorded in %s", name, res.Dropped, process.MissingName(data, name))
362 }
363 return nil
364 }
365 366 // utxoDirs is where one chain's dataset lives: the shared prefix's snapshots
367 // and diffs first, the chain's own second.
368 func utxoDirs(data, chainName string) (sets, diffs []string) {
369 utxo := filepath.Join(data, "utxo")
370 return []string{filepath.Join(utxo, "canonical"), filepath.Join(utxo, "chain-"+chainName)},
371 []string{filepath.Join(utxo, "diff", "shared"), filepath.Join(utxo, "diff", chainName)}
372 }
373 374 // utxoSources is the checkpoint chain in each chain's directory, if one is
375 // there. An instance that holds no UTXO data answers no query for that chain.
376 func utxoSources(data string, names []string) map[string]service.UTXOSource {
377 out := make(map[string]service.UTXOSource, len(names))
378 for _, name := range names {
379 sets, _ := utxoDirs(data, name)
380 out[name] = &service.DiskUTXO{Dirs: sets}
381 }
382 return out
383 }
384 385 // fill syncs headers and then bodies over one connection per chain, because a
386 // node refuses a second connection from the same address seconds after the
387 // first.
388 func fill(ctx context.Context, chainInfo chains.Chain, headers *store.HeaderStore, filterStore *filterstore.Store, bodies *store.BlockStore, staged *staging.Log, addrs []string, connected string, p *v2peer.Peer, lg *logging.Logger, progress time.Duration, useV2, doFilters, filtersOnly bool) error {
389 tip, tipHash, _ := headers.HeaderTip()
390 lg.Infof("fill %s: syncing headers from %d (%x)", chainInfo.Name, tip, [32]byte(tipHash))
391 if err := p.SyncHeaders(headers, lg.Logf); err != nil {
392 // A peer that drops the connection after the handshake costs one
393 // connection, not the fill: the blocks that need filling are the ones
394 // above the headers this instance already holds, and the pool opens its
395 // own lanes.
396 if tip, _, ok := headers.HeaderTip(); !ok {
397 _ = p.Close()
398 return fmt.Errorf("headers: %w", err)
399 } else {
400 lg.Errorf("fill %s: headers: %v (continuing from %d)", chainInfo.Name, err, tip)
401 }
402 }
403 if tip, _, ok := headers.HeaderTip(); ok {
404 lg.Infof("fill %s: headers to %d", chainInfo.Name, tip)
405 }
406 // The filter chain comes next, over the same connection, before the fill
407 // takes it: a filter is committed by the header chain, so fetching it and
408 // checking it against the fold is the same guarantee as building it, and it
409 // needs neither the UTXO set nor the scripts in memory.
410 if doFilters {
411 // A node decides whether to answer from its own services, and a node
412 // that does not advertise compact filters disconnects the peer that
413 // asks. So the bit is the gate for asking at all.
414 if p.Services()&nodeCompactFilters == 0 {
415 lg.Warnf("fill %s: %s does not serve compact filters, so none are synced", chainInfo.Name, connected)
416 } else {
417 start := time.Now()
418 res, err := filtersync.Sync(ctx, p, headers, filterStore, lg.Logf)
419 if err != nil {
420 lg.Errorf("filters %s: %v", chainInfo.Name, err)
421 } else {
422 lg.Infof("filters %s: %d from %d to %d in %s", chainInfo.Name, res.Filters, res.From, res.To, time.Since(start).Round(time.Second))
423 }
424 }
425 }
426 if filtersOnly {
427 return nil
428 }
429 peers := make([]filler.Peer, 0, len(addrs))
430 for _, a := range addrs {
431 peers = append(peers, filler.Peer{Addr: a})
432 }
433 pool, err := filler.NewPool(filler.PoolConfig{
434 Chain: chainInfo.Name, Profile: chainInfo.Profile, Headers: headers, Bodies: bodies,
435 Staging: staged, Peers: peers, Lanes: len(peers), V2: useV2,
436 Logf: lg.Logf, Tracef: lg.Tracef, Warnf: lg.Warnf, ProgressEvery: progress,
437 })
438 if err != nil {
439 _ = p.Close()
440 return err
441 }
442 if err := p.Err(); err == nil {
443 pool.Reuse(connected, p)
444 } else {
445 lg.Warnf("fill %s: %s ended after the handshake (%v), lanes will dial", chainInfo.Name, connected, err)
446 _ = p.Close()
447 }
448 start := time.Now()
449 if err := pool.Run(ctx); err != nil {
450 return fmt.Errorf("blocks: %w", err)
451 }
452 elapsed := time.Since(start)
453 rate := float64(pool.Done()) / elapsed.Seconds()
454 lg.Infof("fill %s: %d bodies in %s (%.0f/s) from %d peer(s), %d failed",
455 chainInfo.Name, pool.Done(), elapsed.Round(time.Millisecond), rate, len(peers), pool.Failed())
456 return pool.Close()
457 }
458 459 // chainListOf splits and checks a -chains flag.
460 func chainListOf(s string) ([]string, error) {
461 var out []string
462 seen := map[string]bool{}
463 for _, name := range strings.Split(s, ",") {
464 name = strings.TrimSpace(name)
465 if name == "" {
466 continue
467 }
468 if seen[name] {
469 continue
470 }
471 if _, err := chains.ByName(name); err != nil {
472 return nil, err
473 }
474 seen[name] = true
475 out = append(out, name)
476 }
477 if len(out) == 0 {
478 return nil, fmt.Errorf("no chains named")
479 }
480 return out, nil
481 }
482 483 // peersOf reads a peer flag into one address list per chain.
484 //
485 // The form is chain=host:port, because a two-chain instance fills from two
486 // different nodes and the address alone does not say which chain it serves. On
487 // a single-chain instance a bare address is that chain's, which keeps the
488 // one-chain command line short.
489 func peersOf(s string, names []string) (map[string][]string, error) {
490 out := map[string][]string{}
491 for _, e := range strings.Split(s, ",") {
492 e = strings.TrimSpace(e)
493 if e == "" {
494 continue
495 }
496 chain, addr, ok := strings.Cut(e, "=")
497 if !ok {
498 if len(names) != 1 {
499 return nil, fmt.Errorf("%q names no chain; write chain=host:port on an instance with %d chains", e, len(names))
500 }
501 out[names[0]] = append(out[names[0]], e)
502 continue
503 }
504 chain, addr = strings.TrimSpace(chain), strings.TrimSpace(addr)
505 known := false
506 for _, n := range names {
507 if n == chain {
508 known = true
509 break
510 }
511 }
512 if !known {
513 return nil, fmt.Errorf("%q is not one of this instance's chains (%s)", chain, strings.Join(names, ","))
514 }
515 out[chain] = append(out[chain], addr)
516 }
517 return out, nil
518 }
519 520 func readKey(path string) (ed25519.PrivateKey, error) {
521 seed, err := os.ReadFile(path)
522 if err != nil {
523 return nil, fmt.Errorf("key: %w", err)
524 }
525 raw, err := hex.DecodeString(strings.TrimSpace(string(seed)))
526 if err != nil || len(raw) != ed25519.SeedSize {
527 return nil, fmt.Errorf("key: %s is not a 32-byte hex seed", path)
528 }
529 return ed25519.NewKeyFromSeed(raw), nil
530 }
531 532 // openBodies opens the block store, verifying every block on disk only when the
533 // operator asks: the pass is linear in the store, so a 600 GB dataset takes
534 // hours to open and every restart pays it again.
535 func openBodies(data string, verify bool) (*store.BlockStore, error) {
536 if verify {
537 return store.NewBlockStore(filepath.Join(data, "blocks"))
538 }
539 return store.NewBlockStoreTrusting(filepath.Join(data, "blocks"))
540 }
541 542 // nodeCompactFilters is NODE_COMPACT_FILTERS: a peer sets it when it will answer
543 // getcfheaders and getcfilters. btcd's wire package carries the messages and not
544 // this flag.
545 const nodeCompactFilters uint64 = 1 << 6
546 547 // report is the heartbeat line: what the process holds and what it has served.
548 func report(lg *logging.Logger, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, staged map[string]*staging.Log) string {
549 st := lg.Stats()
550 var stagedBodies int
551 var stagedBytes int64
552 for _, name := range names {
553 if l, ok := staged[name]; ok {
554 stagedBodies += l.Len()
555 stagedBytes += l.Bytes()
556 }
557 }
558 var b strings.Builder
559 fmt.Fprintf(&b, "blocks=%d filters=%d staged=%d staged_bytes=%d requests=%d bytes_out=%d refused=%d failed=%d heap_mb=%d goroutines=%d",
560 bodies.Len(), filters.Len(), stagedBodies, stagedBytes,
561 st.Requests, st.Bytes, st.Refused, st.Failed, heapMB(), runtime.NumGoroutine())
562 for _, name := range names {
563 if tip, _, ok := headers[name].HeaderTip(); ok {
564 fmt.Fprintf(&b, " %s_tip=%d", name, tip)
565 } else {
566 fmt.Fprintf(&b, " %s_tip=none", name)
567 }
568 }
569 return b.String()
570 }
571 572 // heapMB is the live heap, which is the number that says whether a running
573 // instance is growing without bound.
574 func heapMB() uint64 {
575 var m runtime.MemStats
576 runtime.ReadMemStats(&m)
577 return m.HeapAlloc >> 20
578 }
579