Hedera编程实现:如何将时间戳转换为对应区块号?
如何在Hedera中通过时间戳编程获取对应区块号
背景
根据HIP-415规范,Hedera的区块由共识节点生成的「记录文件」分组而成,同一记录文件内的交易归属于同一个区块,区块生成间隔约为2秒。若要调用eth_getBlockByNumber RPC接口,需将目标时间戳转换为对应的区块号。
编程实现方案
最可靠的实现方式是借助Hedera镜像节点API完成时间戳到区块号的映射,具体步骤如下:
1. 构造镜像节点查询请求
Hedera镜像节点提供了按时间范围查询区块的接口,你可以通过GET请求传入目标时间戳,获取包含该时间点的区块信息。
以测试网为例,请求格式如下:
curl "https://testnet.mirrornode.hedera.com/api/v1/blocks?timestamp=gte:{目标纳秒时间戳}&limit=1"
- 注意:Hedera使用纳秒级时间戳,需将你的目标时间戳(如Unix秒级时间戳)转换为纳秒(乘以10^9)。
- 参数
timestamp=gte:{值}表示获取时间戳大于等于该值的第一个区块,limit=1确保只返回最匹配的单个区块。
2. 解析响应提取区块号
接口返回的JSON响应中,blocks[0].number字段即为对应的区块号。示例响应结构:
{ "blocks": [ { "number": 4507206, "timestamp": { "from": 1683707272012122604, "to": 1683707273700400000 } } ] }
3. 代码示例(JavaScript)
async function getBlockNumberByTimestamp(targetTimestampSeconds) { // 转换为纳秒级时间戳 const targetNanos = BigInt(targetTimestampSeconds) * BigInt(1e9); // 替换为对应网络的镜像节点地址 const apiUrl = `https://testnet.mirrornode.hedera.com/api/v1/blocks?timestamp=gte:${targetNanos}&limit=1`; const response = await fetch(apiUrl); const result = await response.json(); if (result.blocks?.length > 0) { return result.blocks[0].number; } throw new Error("未找到匹配的区块"); } // 使用示例:查询2023-05-10T08:27:53 UTC对应的区块号(秒级时间戳为1683707273) getBlockNumberByTimestamp(1683707273) .then(blockNum => console.log("对应区块号:", blockNum)) .catch(err => console.error(err));
4. 适配不同网络
切换主网或预览网时,只需替换镜像节点API地址:
- 主网:
https://mainnet.mirrornode.hedera.com/api/v1/blocks - 预览网:
https://previewnet.mirrornode.hedera.com/api/v1/blocks
注意事项
- 若目标时间戳恰好处于两个区块的时间间隙,
gte参数会返回下一个区块,这符合eth_getBlockByNumber的使用逻辑(该时间点无交易,最近的有效区块即为下一个)。 - 所有时间戳需以UTC时间为准,Hedera镜像节点的时间统一采用UTC。
内容的提问来源于stack exchange,提问作者bguiz
相关产品推荐
相关产品推荐

