结构字段与同一结构集的其他字段的哈希函数 - GoLang
小伙伴们对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学习网公众号!

- 上一篇
- go-git:创建本地分支的正确方法,模拟“git分支
”的行为?

- 下一篇
- 从 Golang 中的另一个模块覆盖函数
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 魔匠AI
- SEO摘要魔匠AI专注于高质量AI学术写作,已稳定运行6年。提供无限改稿、选题优化、大纲生成、多语言支持、真实参考文献、数据图表生成、查重降重等全流程服务,确保论文质量与隐私安全。适用于专科、本科、硕士学生及研究者,满足多语言学术需求。
- 19次使用
-
- PPTFake答辩PPT生成器
- PPTFake答辩PPT生成器,专为答辩准备设计,极致高效生成PPT与自述稿。智能解析内容,提供多样模板,数据可视化,贴心配套服务,灵活自主编辑,降低制作门槛,适用于各类答辩场景。
- 35次使用
-
- Lovart
- SEO摘要探索Lovart AI,这款专注于设计领域的AI智能体,通过多模态模型集成和智能任务拆解,实现全链路设计自动化。无论是品牌全案设计、广告与视频制作,还是文创内容创作,Lovart AI都能满足您的需求,提升设计效率,降低成本。
- 35次使用
-
- 美图AI抠图
- 美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
- 43次使用
-
- PetGPT
- SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
- 44次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览