package pow import ( "bytes" "crypto/sha256" "encoding" "errors" "math" "runtime" "strconv" "sync" "sync/atomic" ) // marker is how the nonce appears in canonical JSON: its key, then the number. // Keys are sorted, so the same bytes surround it on every attempt. const marker = `"pow":` // chunk is how many nonces a worker takes at a time. Chunks are handed out in // ascending order, which is what lets parallel mining still return the // smallest nonce. const chunk = 1 << 14 // parallelFrom is the difficulty from which mining uses several cores; below // it the answer comes in microseconds and starting goroutines would cost more. const parallelFrom = 14 // noMidstate makes every attempt hash the whole record, as a hash that cannot // save its state would force; only tests set it. var noMidstate bool // ErrExhausted means no nonce up to the limit was good enough. var ErrExhausted = errors.New("pow: no nonce found within the limit") // Mine returns the smallest nonce n >= 0 for which sha256 of b, with n written // in place of the 0 after "pow":, has at least bits leading zero bits. b is the // canonical encoding of a record whose nonce field is currently 0; it must // contain `"pow":0` exactly once. The result is exactly what trying 0, 1, 2, ... // one by one would find, just much faster: the bytes before the nonce are // hashed once, and every attempt only hashes the number and what follows it, // on every core but one (so the rest of the node keeps running). func Mine(b []byte, bits int, limit uint64) (uint64, error) { prefix, suffix, err := split(b) if err != nil { return 0, err } if bits <= 0 { return 0, nil } workers := 1 if bits >= parallelFrom { workers = max(1, runtime.GOMAXPROCS(0)-1) } var next atomic.Uint64 var best atomic.Uint64 best.Store(math.MaxUint64) var wg sync.WaitGroup for w := 0; w < workers; w++ { wg.Add(1) go func() { defer wg.Done() m := newMiner(prefix, suffix, bits) for { start := (next.Add(1) - 1) * chunk if start > limit || start >= best.Load() { return } end := start + chunk // exclusive if end > limit+1 || end < start { end = limit + 1 } if n, ok := m.scan(start, end, &best); ok { for cur := best.Load(); n < cur && !best.CompareAndSwap(cur, n); cur = best.Load() { } } } }() } wg.Wait() if n := best.Load(); n != math.MaxUint64 { return n, nil } return 0, ErrExhausted } // split cuts b around the nonce: everything up to and including `"pow":` and // everything after the 0. func split(b []byte) (prefix, suffix []byte, err error) { if bytes.Count(b, []byte(marker)) != 1 { return nil, nil, errors.New(`pow: the record must contain "pow": exactly once`) } i := bytes.Index(b, []byte(marker)) + len(marker) if i >= len(b) || b[i] != '0' || (i+1 < len(b) && b[i+1] >= '0' && b[i+1] <= '9') { return nil, nil, errors.New(`pow: the nonce must be 0 while mining`) } return b[:i], b[i+1:], nil } // miner hashes attempts for one record. Each worker has its own. type miner struct { bits int state []byte // sha256 state after the whole 64-byte blocks of the prefix; nil if unavailable tail []byte // the rest of the prefix suffix []byte h encoding.BinaryUnmarshaler hash interface { Write([]byte) (int, error) Sum([]byte) []byte } msg []byte sum [sha256.Size]byte num []byte // whole is the full prefix, used when the hash cannot save its state. whole []byte } func newMiner(prefix, suffix []byte, bits int) *miner { m := &miner{bits: bits, suffix: suffix, whole: prefix, num: make([]byte, 0, 20)} h := sha256.New() u, canRestore := h.(encoding.BinaryUnmarshaler) s, canSave := h.(encoding.BinaryMarshaler) if canRestore && canSave && !noMidstate { full := len(prefix) &^ (sha256.BlockSize - 1) h.Write(prefix[:full]) if state, err := s.MarshalBinary(); err == nil { m.state, m.tail, m.h, m.hash = state, prefix[full:], u, h m.msg = make([]byte, 0, len(m.tail)+20+len(suffix)) return m } } m.msg = make([]byte, 0, len(prefix)+20+len(suffix)) return m } // scan tries nonces from..to-1 in order and returns the first that works. It // gives up early once some worker has found a smaller nonce than any left here. func (m *miner) scan(from, to uint64, best *atomic.Uint64) (uint64, bool) { for n := from; n < to; n++ { if n&255 == 0 && n >= best.Load() { return 0, false } m.num = strconv.AppendUint(m.num[:0], n, 10) if m.good(m.num) { return n, true } } return 0, false } func (m *miner) good(num []byte) bool { var sum []byte if m.state != nil { m.msg = append(append(append(m.msg[:0], m.tail...), num...), m.suffix...) if m.h.UnmarshalBinary(m.state) != nil { return false } m.hash.Write(m.msg) sum = m.hash.Sum(m.sum[:0]) } else { m.msg = append(append(append(m.msg[:0], m.whole...), num...), m.suffix...) s := sha256.Sum256(m.msg) sum = s[:] } return zeroBits(sum) >= m.bits }