go实现简单区块链part-1: https://jeiwan.cc/posts/building-blockchain-in-go-part-1/
学习函数:
hash := sha256.Sum256(headers)
go的json解析以及marshal, unmarshal操作:https://blog.csdn.net/zxy_666/article/details/80173288
顺便学习了一下package hash256, package encoding, package hash
在package hash看到的example code:
package main
import (
"bytes"
"crypto/sha256"
"encoding"
"fmt"
"log"
)
func main() {
const (
input1 = "The tunneling gopher digs downwards, "
input2 = "unaware of what he will find."
)
first := sha256.New()
first.Write([]byte(input1))
marshaler, ok := first.(encoding.BinaryMarshaler)
if !ok {
log.Fatal("first does not implement encoding.BinaryMarshaler")
}
state, err := marshaler.MarshalBinary()
if err != nil {
log.Fatal("unable to marshal hash:", err)
}
second := sha256.New()
unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
if !ok {
log.Fatal("second does not implement encoding.BinaryUnmarshaler")
}
if err := unmarshaler.UnmarshalBinary(state); err != nil {
log.Fatal("unable to unmarshal hash:", err)
}
first.Write([]byte(input2))
second.Write([]byte(input2))
fmt.Printf("%x\n", first.Sum(nil))
fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
}
hash.Hash的定义如下:
type Hash interface { // Write (via the embedded io.Writer interface) adds more data to the running hash. // It never returns an error. io.Writer // Sum appends the current hash to b and returns the resulting slice. // It does not change the underlying hash state. Sum(b []byte) []byte // Reset resets the Hash to its initial state. Reset() // Size returns the number of bytes Sum will return. Size() int // BlockSize returns the hash's underlying block size. // The Write method must be able to accept any amount // of data, but it may operate more efficiently if all writes // are a multiple of the block size. BlockSize() int }
其中有一个io.Writer不同寻常的不是函数,这是embaded interface:
The Hash interface embeds the Writer interface. Therefore, any type that wants to implement the Hash interface, also needs to implement the Writer interface containing the Write method.
The reason for the Write Method is that you can calculate hashes of anything that can be written. For example, you can calculate the hash of the formatted representation of an object (by using the fmt package), or you can calculate the hash of the json representation (by using the json package), etc.
hash.Hash是一个interface, 其中 sha256.New()返回一个实现了Hash的Hash变量,这个变量在sha256.New()的源码中是类型为digest的,它还实现了encoding.BinaryMarshaler和encoding.BinaryUnmarshaler接口的方法,
marshaler, ok := first.(encoding.BinaryMarshaler)这一句是Type assertions : https://tour.golang.org/methods/15
利用Type assertions返回一个可以调用encoding.BinaryMarshaler和encoding.BinaryUnmarshaler的东西