forked from ishbir/bmutil
/
nonce.go
43 lines (36 loc) · 941 Bytes
/
nonce.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
// Copyright (c) 2016 Daniel Krawisz.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package pow
import (
"encoding/binary"
"io"
)
type Target uint64
// Nonce represents a number at the head of an object message which
// is used for the proof of work.
type Nonce uint64
// Bytes returns the nonce as a bite array, as specified by the Bitmessage
// protocol.
func (n Nonce) Bytes() []byte {
nonceBytes := make([]byte, 8)
binary.BigEndian.PutUint64(nonceBytes, uint64(n))
return nonceBytes
}
// Encode encodes a nonce to a writer.
func (n Nonce) Encode(w io.Writer) error {
_, err := w.Write(n.Bytes())
if err != nil {
return err
}
return nil
}
// DecodeNonce decodes a nonce from a reader.
func DecodeNonce(r io.Reader) (Nonce, error) {
var b [8]byte
_, err := io.ReadFull(r, b[:])
if err != nil {
return 0, err
}
return Nonce(binary.BigEndian.Uint64(b[:])), nil
}