结构字段与同一结构集的其他字段的哈希函数 - GoLang
来源:stackoverflow
时间:2024-02-12 15:09:25 467浏览 收藏
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《结构字段与同一结构集的其他字段的哈希函数 - GoLang》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
我是 golang 新手,正开始尝试构建一个简单的区块链。我在创建块的哈希时遇到问题。任何人都可以帮助我如何将结构集的其他字段传递到同一结构中的 hash() 函数中,或者如果它需要以某种方式位于结构之外,或者甚至可能...... p>
块结构
type block struct {
index int
prevhash string
txs []tx
timestamp int64
hash string
}
设置结构示例
block{
index: 0,
prevhash: "genesis",
txs: []tx{},
timestamp: time.now().unix(),
hash: hash(/* how do i pass the other fields data here... */),
}
我的哈希函数
func hash(text string) string {
hash := md5.sum([]byte(text))
return hex.encodetostring(hash[:])
}
我的导入(如果有帮助)
import ( "crypto/md5" "encoding/hex" "fmt" "time" )
正确答案
有很多方法可以做到这一点,但是当您正在寻找一种简单的方法来做到这一点时,您可以只序列化数据,对其进行散列并分配。最简单的方法是编组 block 类型,对结果进行哈希处理,然后将其分配给 hash 字段。
就我个人而言,我更喜欢通过拆分构成哈希的数据来使其更加明确,并将这种类型嵌入到块类型本身中,但这实际上取决于您。请注意,json 编组映射可能不是确定性的,因此根据您的 tx 类型中的内容,您可能需要进行更多工作。
无论如何,对于嵌入类型,它看起来像这样:
// you'll rarely interact with this type directly, never outside of hashing
type inblock struct {
index int `json:"index"`
prevhash string `json:"prevhash"`
txs []tx `json:"txs"`
timestamp int64 `json:"timestamp"`
}
// almost identical in to the existing block type
type block struct {
inblock // embed the block fields
hash string
}
现在,哈希函数可以变成 block 类型本身的接收函数:
// calculatehash will compute the hash, set it on the block field, returns an error if we can't serialise the hash data
func (b *block) calculatehash() error {
data, err := json.marshal(b.inblock) // marshal the inblock data
if err != nil {
return err
}
hash := md5.sum(data)
b.hash = hex.encodetostring(hash[:])
return nil
}
现在唯一真正的区别是如何初始化 block 类型:
block := block{
inblock: inblock{
index: 0,
prevhash: "genesis",
txs: []tx{},
timestamp: time.now().unix(),
},
hash: "", // can be omitted
}
if err := block.calculatehash(); err != nil {
panic("something went wrong: " + err.error())
}
// block now has the hash set
要访问 block 变量上的字段,您无需指定 inblock,因为 block 类型不包含任何名称会掩盖其嵌入的类型字段的字段,因此此方法有效:
txs := block.txs // just as well as this txs := block.inblock.txs
如果没有嵌入类型,它最终会看起来像这样:
type block struct {
index int `json:"index"`
prevhash string `json:"prevhash"`
txs []tx `json:"txs"`
timestamp int64 `json:"timestamp"`
hash string `json:"-"` // exclude from json mashalling
}
然后哈希值看起来像这样:
func (b *block) calculatehash() error {
data, err := json.marshal(b)
if err != nil {
return err
}
hash := md5.sum(data)
b.hash = hex.encodetostring(hash[:])
return nil
}
通过这种方式,底层的 block 类型可以像您现在所做的那样使用。至少在我看来,缺点是以人类可读格式调试/转储数据有点烦人,因为由于 json:"-" 标签,哈希永远不会包含在 json 转储中。您可以通过仅在 json 输出中包含 hash 字段(如果已设置)来解决此问题,但这确实会导致哈希值未正确设置的奇怪错误。
关于地图评论
因此,在 golang 中迭代映射是不确定的。您可能知道,确定性在区块链应用程序中非常重要,而地图通常是非常常用的数据结构。在可以让多个节点处理相同工作负载的情况下处理它们时,每个节点生成相同的哈希值绝对至关重要(显然,前提是它们执行相同的工作)。假设您决定定义块类型,无论出于何种原因,将 txs 作为按 id 的映射(因此 txs map[uint64]tx),在这种情况下,不能保证 json 输出在所有内容上都相同节点。如果是这种情况,您需要以解决此问题的方式编组/解组数据:
// a new type that you'll only use in custom marshalling
// txs is a slice here, using a wrapper type to preserve id
type blockjson struct {
index int `json:"index"`
prevhash string `json:"prevhash"`
txs []txid `json:"txs"`
timestamp int64 `json:"timestamp"`
hash string `json:"-"`
}
// txid is a type that preserves both tx and id data
// tx is a pointer to prevent copying the data later on
type txid struct {
tx *tx `json:"tx"`
id uint64 `json:"id"`
}
// not the json tags are gone
type block struct {
index int
prevhash string
txs map[uint64]tx // as a map
timestamp int64
hash string
}
func (b block) marshaljson() ([]byte, error) {
cpy := blockjson{
index: b.index,
prevhash: b.prevhash,
txs: make([]txid, 0, len(b.txs)), // allocate slice
timestamp: b.timestamp,
}
keys := make([]uint64, 0, len(b.txs)) // slice of keys
for k := range b.txs {
keys = append(keys, k) // add keys to the slice
}
// now sort the slice. i prefer stable, but for int keys sort
// should work just fine
sort.slicestable(keys, func(i, j int) bool {
return keys[i] < keys[j]
}
// now we can iterate over our sorted slice and append to the txs slice ensuring the order is deterministic
for _, k := range keys {
cpy.txs = append(cpy.txs, txid{
tx: &b.txs[k],
id: k,
})
}
// now we've copied over all the data, we can marshal it:
return json.marshal(cpy)
}
对于解组也必须执行相同的操作,因为序列化的数据不再与我们原始的 block 类型兼容:
func (b *block) unmarshaljson(data []byte) error {
wrapper := blockjson{} // the intermediary type
if err := json.unmarshal(data, &wrapper); err != nil {
return err
}
// copy over fields again
b.index = wrapper.index
b.prevhash = wrapper.prevhash
b.timestamp = wrapper.timestamp
b.txs = make(map[uint64]tx, len(wrapper.txs)) // allocate map
for _, tx := range wrapper.txs {
b.txs[tx.id] = *tx.tx // copy over values to build the map
}
return nil
}
您可以重新分配整个 block 变量,而不是逐个字段复制,特别是因为我们并不真正关心 hash 字段是否保留其值:
func (b *Block) UnmarshalJSON(data []byte) error {
wrapper := blockJSON{} // the intermediary type
if err := json.Unmarshal(data, &wrapper); err != nil {
return err
}
*b = Block{
Index: wrapper.Index,
PrevHash: wrapper.PrevHash,
Txs: make(map[uint64]Tx, len(wrapper.Txs)),
Timestamp: wrapper.Timestamp,
}
for _, tx := range wrapper.Txs {
b.Txs[tx.ID] = *tx.Tx // populate map
}
return nil
}
但是,正如您可能会说的那样:避免使用您想要散列的类型的映射,或者实现不同的方法以更可靠的方式获取散列
本篇关于《结构字段与同一结构集的其他字段的哈希函数 - GoLang》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习