结构字段与同一结构集的其他字段的哈希函数 - 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分支 - 上一篇
- go-git:创建本地分支的正确方法,模拟“git分支
”的行为?
- 下一篇
- 从 Golang 中的另一个模块覆盖函数
-
- Golang · Go问答 | 43分钟前 | go ·
- Go runtime/pprof调整采样间隔而不误读结果的参数边界
- 286浏览 收藏
-
- Golang · Go问答 | 50分钟前 |
- Go runtime/pprof读取阻塞 Profile 识别等待点的排查指南
- 411浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go runtime/pprof把请求标签写入 CPU Profile的分析方法
- 337浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go testing/fstest理解测试文件系统的链接边界的设计说明
- 279浏览 收藏
-
- Golang · Go问答 | 1小时前 | 单元测试 · go ·
- Go testing/fstest用 MapFS 构造轻量文件测试的实践示例
- 116浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · Go 路径检查 fs.FS testing/fstest
- Go testing/fstest发现 FS 实现的路径错误的检查方法
- 486浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go testing.T TempDir用 Setenv 隔离并行子测试环境的目录方案
- 480浏览 收藏
-
- Golang · Go问答 | 2小时前 | go · testing · Go测试临时目录 Go testing.T TempDir
- Go testing.T TempDir让临时目录随测试自动回收的使用方法
- 367浏览 收藏
-
- Golang · Go问答 | 2小时前 | go · testing · Go testing.T Cleanup Go测试辅助函数 测试失败定位
- Go testing.T Cleanup把失败位置指向测试调用方的诊断方法
- 356浏览 收藏
-
- Golang · Go问答 | 2小时前 | go · testing · Go testing.T Cleanup
- Go testing.T Cleanup按注册逆序释放测试资源的组织方法
- 343浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 124次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 196次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 142次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 116次使用
-
- CMMLU
- 深入了解CMMLU中文评估基准,涵盖67个学科主题,提供数据集下载、Zero-shot/Five-shot评估方法及排行榜,助力优化中文语言模型性能。
- 104次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
-
- Go 取 range 变量地址为什么得到重复指针
- 2026-09-07 501浏览
-
- Go net.Conn 写入超时为何仍会卡住:SetWriteDeadline、部分写入与连接复用检查
- 2026-08-30 501浏览

