web3.shh.subscribe - 订阅whisper消息
优质
小牛编辑
126浏览
2023-12-01
订阅收到的whisper消息。
调用:
web3.shh.subscribe('messages', options [, callback])
参数:
- "messages" - String: 订阅类型
options
:Object - 订阅选项,有如下字段:- symKeyID - String: 用于消息解密的对称密钥
- privateKeyID - String: 用于消息解密的私钥
- sig - String ,可选,签名的公钥,用于验证
- topics- Array,可选,用于过滤消息的主题数组, 每个主题必须是4字节长的16进制字符串
- minPow - Number ,可选,处理收到的消息所需的最小PoW
- allowP2P - Boolean ,可选,是否允许处理端对端消息
callback
- Function: 可选的回调函数,其第一个参数为错误对象,第二个参数为返回值(optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription, and the subscription itself as 3 parameter.
通知返回值:
Object
- 接收到的消息,其结构如下:
- hash - String: 封装后消息的哈希签名
- sig - String: 用于对消息进行签名的公钥
- recipientPublicKey - String: 接收人的公钥
- timestamp - String: 消息创建的unix时间戳
- ttl - Number: 以秒为单位的消息存活时间
- topic - String: 4字节的16进制字符串,消息主题.
- payload - String: 解密的负载
- padding - Number: 可选,补齐长度
- pow - Number: PoW值
示例代码:
web3.shh.subscribe('messages', {
symKeyID: 'bf31b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f',
sig: '0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b11aeabcd3abbc7b2bc2bb967368a68e9c6',
ttl: 20,
topics: ['0xffddaa11'],
minPow: 0.8,
}, function(error, message, subscription){
console.log(message);
> {
"hash": "0x4158eb81ad8e30cfcee67f20b1372983d388f1243a96e39f94fd2797b1e9c78e",
"padding": "0xc15f786f34e5cef0fef6ce7c1185d799ecdb5ebca72b3310648c5588db2e99a0d73301c7a8d90115a91213f0bc9c72295fbaf584bf14dc97800550ea53577c9fb57c0249caeb081733b4e605cdb1a6011cee8b6d8fddb972c2b90157e23ba3baae6c68d4f0b5822242bb2c4cd821b9568d3033f10ec1114f641668fc1083bf79ebb9f5c15457b538249a97b22a4bcc4f02f06dec7318c16758f7c008001c2e14eba67d26218ec7502ad6ba81b2402159d7c29b068b8937892e3d4f0d4ad1fb9be5e66fb61d3d21a1c3163bce74c0a9d16891e2573146aa92ecd7b91ea96a6987ece052edc5ffb620a8987a83ac5b8b6140d8df6e92e64251bf3a2cec0cca",
"payload": "0xdeadbeaf",
"pow": 0.5371803278688525,
"recipientPublicKey": null,
"sig": null,
"timestamp": 1496991876,
"topic": "0x01020304",
"ttl": 50
}
})
// or
.on('data', function(message){ ... });