mirror of https://github.com/status-im/go-waku.git
Initial commit
This commit is contained in:
parent
0c518b0df2
commit
ccff3dc8f8
|
@ -0,0 +1 @@
|
|||
# Changelog
|
|
@ -0,0 +1,205 @@
|
|||
go-waku is licensed under the Apache License version 2
|
||||
Copyright (c) 2018 Status Research & Development GmbH
|
||||
-----------------------------------------------------
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2018 Status Research & Development GmbH
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,25 @@
|
|||
go-waku is licensed under the MIT License
|
||||
Copyright (c) 2018 Status Research & Development GmbH
|
||||
-----------------------------------------------------
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2018 Status Research & Development GmbH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,13 @@
|
|||
module github.com/status-im/go-waku
|
||||
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/ethereum/go-ethereum v1.10.1
|
||||
github.com/ipfs/go-log/v2 v2.1.1
|
||||
github.com/libp2p/go-libp2p v0.13.0
|
||||
github.com/libp2p/go-libp2p-core v0.8.5
|
||||
github.com/multiformats/go-multiaddr v0.3.1
|
||||
github.com/multiformats/go-multiaddr-net v0.2.0
|
||||
google.golang.org/protobuf v1.25.0
|
||||
)
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
golog "github.com/ipfs/go-log/v2"
|
||||
"github.com/libp2p/go-libp2p-core/crypto"
|
||||
"github.com/status-im/go-waku/waku/v2/node"
|
||||
//node "waku/v2/node"
|
||||
)
|
||||
|
||||
func main() {
|
||||
golog.SetAllLoggers(golog.LevelInfo) // Change to INFO for extra info
|
||||
|
||||
hostAddr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:5555")
|
||||
extAddr, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:5555")
|
||||
|
||||
var r io.Reader
|
||||
r = rand.Reader
|
||||
prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.ECDSA, -1, r)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
wakuNode, err := node.New(prvKey, hostAddr, extAddr)
|
||||
|
||||
if err != nil {
|
||||
fmt.Print(err)
|
||||
}
|
||||
|
||||
_ = wakuNode // TODO: Just to shut up the compiler. Do a proper test case and remove this
|
||||
|
||||
select {} // Run forever
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package node
|
||||
|
||||
import (
|
||||
"github.com/libp2p/go-libp2p-core/host"
|
||||
"github.com/libp2p/go-libp2p-core/peerstore"
|
||||
)
|
||||
|
||||
type Connectedness string
|
||||
|
||||
const (
|
||||
// NotConnected: default state for a new peer. No connection and no further information on connectedness.
|
||||
NotConnected Connectedness = "NotConnected"
|
||||
// CannotConnect: attempted to connect to peer, but failed.
|
||||
CannotConnect Connectedness = "CannotConnect"
|
||||
// CanConnect: was recently connected to peer and disconnected gracefully.
|
||||
CanConnect Connectedness = "CanConnect"
|
||||
// Connected: actively connected to peer.
|
||||
Connected Connectedness = "Connected"
|
||||
)
|
||||
|
||||
/*
|
||||
type
|
||||
ConnectionBook* = object of PeerBook[Connectedness]
|
||||
*/
|
||||
|
||||
type WakuPeerStore struct {
|
||||
connectionBook peerstore.Peerstore
|
||||
}
|
||||
|
||||
type PeerManager struct {
|
||||
sw host.Host
|
||||
peerStore *WakuPeerStore
|
||||
}
|
||||
|
||||
func NewWakuPeerStore() *WakuPeerStore {
|
||||
p := new(WakuPeerStore)
|
||||
return p
|
||||
}
|
||||
|
||||
func NewPeerManager(sw host.Host) *PeerManager {
|
||||
peerStore := NewWakuPeerStore()
|
||||
p := new(PeerManager)
|
||||
p.sw = sw
|
||||
p.peerStore = peerStore
|
||||
return p
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
package node
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdsa"
|
||||
crand "crypto/rand"
|
||||
mrand "math/rand"
|
||||
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto/ecies"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol"
|
||||
)
|
||||
|
||||
type KeyKind string
|
||||
|
||||
const (
|
||||
Symmetric KeyKind = "Symmetric"
|
||||
Asymmetric KeyKind = "Asymmetric"
|
||||
None KeyKind = "None"
|
||||
)
|
||||
|
||||
type KeyInfo struct {
|
||||
kind KeyKind
|
||||
symKey []byte
|
||||
privKey ecdsa.PrivateKey
|
||||
}
|
||||
|
||||
// NOTICE: Extracted from status-go
|
||||
|
||||
const aesNonceLength = 12
|
||||
const aesKeyLength = 32
|
||||
|
||||
// Decrypts a message with a topic key, using AES-GCM-256.
|
||||
// nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
|
||||
func decryptSymmetric(payload []byte, key []byte) ([]byte, error) {
|
||||
// symmetric messages are expected to contain the 12-byte nonce at the end of the payload
|
||||
if len(payload) < aesNonceLength {
|
||||
return nil, errors.New("missing salt or invalid payload in symmetric message")
|
||||
}
|
||||
|
||||
salt := payload[len(payload)-aesNonceLength:]
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decrypted, err := aesgcm.Open(nil, salt, payload[:len(payload)-aesNonceLength], nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return decrypted, nil
|
||||
}
|
||||
|
||||
// Decrypts an encrypted payload with a private key.
|
||||
func decryptAsymmetric(payload []byte, key *ecdsa.PrivateKey) ([]byte, error) {
|
||||
decrypted, err := ecies.ImportECDSA(key).Decrypt(payload, nil, nil)
|
||||
if err == nil {
|
||||
return nil, err
|
||||
}
|
||||
return decrypted, err
|
||||
}
|
||||
|
||||
func decodePayload(message *protocol.WakuMessage, keyInfo *KeyInfo) ([]byte, error) {
|
||||
switch *message.Version {
|
||||
case uint32(0):
|
||||
return message.Payload, nil
|
||||
case uint32(1):
|
||||
switch keyInfo.kind {
|
||||
case Symmetric:
|
||||
decoded, err := decryptSymmetric(message.Payload, keyInfo.symKey)
|
||||
if err != nil {
|
||||
return nil, errors.New("Couldn't decrypt using symmetric key")
|
||||
} else {
|
||||
return decoded, nil
|
||||
}
|
||||
case Asymmetric:
|
||||
decoded, err := decryptAsymmetric(message.Payload, &keyInfo.privKey)
|
||||
if err != nil {
|
||||
return nil, errors.New("Couldn't decrypt using asymmetric key")
|
||||
} else {
|
||||
return decoded, nil
|
||||
}
|
||||
case None:
|
||||
return nil, errors.New("Non supported KeyKind")
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Unsupported WakuMessage version")
|
||||
}
|
||||
|
||||
// ValidatePublicKey checks the format of the given public key.
|
||||
func ValidatePublicKey(k *ecdsa.PublicKey) bool {
|
||||
return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
|
||||
}
|
||||
|
||||
// Encrypts and returns with a public key.
|
||||
func encryptAsymmetric(rawPayload []byte, key *ecdsa.PublicKey) ([]byte, error) {
|
||||
if !ValidatePublicKey(key) {
|
||||
return nil, errors.New("invalid public key provided for asymmetric encryption")
|
||||
}
|
||||
encrypted, err := ecies.Encrypt(crand.Reader, ecies.ImportECDSAPublic(key), rawPayload, nil, nil)
|
||||
if err == nil {
|
||||
return encrypted, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Encrypts a payload with a topic key, using AES-GCM-256.
|
||||
// nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
|
||||
func encryptSymmetric(rawPayload []byte, key []byte) ([]byte, error) {
|
||||
if !validateDataIntegrity(key, aesKeyLength) {
|
||||
return nil, errors.New("invalid key provided for symmetric encryption, size: " + strconv.Itoa(len(key)))
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
salt, err := generateSecureRandomData(aesNonceLength) // never use more than 2^32 random nonces with a given key
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encrypted := aesgcm.Seal(nil, salt, rawPayload, nil)
|
||||
return append(encrypted, salt...), nil
|
||||
}
|
||||
|
||||
// validateDataIntegrity returns false if the data have the wrong or contains all zeros,
|
||||
// which is the simplest and the most common bug.
|
||||
func validateDataIntegrity(k []byte, expectedSize int) bool {
|
||||
if len(k) != expectedSize {
|
||||
return false
|
||||
}
|
||||
if expectedSize > 3 && containsOnlyZeros(k) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// containsOnlyZeros checks if the data contain only zeros.
|
||||
func containsOnlyZeros(data []byte) bool {
|
||||
for _, b := range data {
|
||||
if b != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// generateSecureRandomData generates random data where extra security is required.
|
||||
// The purpose of this function is to prevent some bugs in software or in hardware
|
||||
// from delivering not-very-random data. This is especially useful for AES nonce,
|
||||
// where true randomness does not really matter, but it is very important to have
|
||||
// a unique nonce for every message.
|
||||
func generateSecureRandomData(length int) ([]byte, error) {
|
||||
x := make([]byte, length)
|
||||
y := make([]byte, length)
|
||||
res := make([]byte, length)
|
||||
|
||||
_, err := crand.Read(x)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if !validateDataIntegrity(x, length) {
|
||||
return nil, errors.New("crypto/rand failed to generate secure random data")
|
||||
}
|
||||
_, err = mrand.Read(y)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if !validateDataIntegrity(y, length) {
|
||||
return nil, errors.New("math/rand failed to generate secure random data")
|
||||
}
|
||||
for i := 0; i < length; i++ {
|
||||
res[i] = x[i] ^ y[i]
|
||||
}
|
||||
if !validateDataIntegrity(res, length) {
|
||||
return nil, errors.New("failed to generate secure random data")
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func encode(rawPayload []byte, keyInfo *KeyInfo, version uint32) ([]byte, error) {
|
||||
switch version {
|
||||
case 0:
|
||||
return rawPayload, nil
|
||||
case 1:
|
||||
switch keyInfo.kind {
|
||||
case Symmetric:
|
||||
encoded, err := encryptSymmetric(rawPayload, keyInfo.symKey)
|
||||
if err != nil {
|
||||
return nil, errors.New("Couldn't encrypt using symmetric key")
|
||||
} else {
|
||||
return encoded, nil
|
||||
}
|
||||
case Asymmetric:
|
||||
encoded, err := encryptAsymmetric(rawPayload, &keyInfo.privKey.PublicKey)
|
||||
if err != nil {
|
||||
return nil, errors.New("Couldn't encrypt using asymmetric key")
|
||||
} else {
|
||||
return encoded, nil
|
||||
}
|
||||
case None:
|
||||
return nil, errors.New("Non supported KeyKind")
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Unsupported WakuMessage version")
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
|
||||
"github.com/libp2p/go-libp2p"
|
||||
"github.com/libp2p/go-libp2p-core/crypto"
|
||||
"github.com/libp2p/go-libp2p-core/host"
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
ma "github.com/multiformats/go-multiaddr"
|
||||
manet "github.com/multiformats/go-multiaddr-net"
|
||||
|
||||
"github.com/status-im/go-waku/waku/v2/protocol"
|
||||
)
|
||||
|
||||
// Default clientId
|
||||
const clientId string = "Go Waku v2 node"
|
||||
|
||||
// XXX: Weird type, should probably be using pubsub Topic object name?
|
||||
type Topic string
|
||||
|
||||
type Message []byte
|
||||
|
||||
type WakuInfo struct {
|
||||
// NOTE One for simplicity, can extend later as needed
|
||||
listenStr string
|
||||
multiaddrStrings []byte
|
||||
}
|
||||
|
||||
type MessagePair struct {
|
||||
a *Topic
|
||||
b *protocol.WakuMessage
|
||||
}
|
||||
|
||||
// NOTE based on Eth2Node in NBC eth2_network.nim
|
||||
type WakuNode struct {
|
||||
peerManager *PeerManager
|
||||
sw host.Host
|
||||
// wakuRelay *WakuRelay
|
||||
// wakuStore *WakuStore
|
||||
// wakuFilter *WakuFilter
|
||||
//wakuSwap *WakuSwap
|
||||
//wakuRlnRelay *WakuRLNRelay
|
||||
peerInfo peer.AddrInfo
|
||||
// libp2pTransportLoops []Future[void] ??
|
||||
// TODO Revisit messages field indexing as well as if this should be Message or WakuMessage
|
||||
messages []MessagePair
|
||||
//filters *Filters
|
||||
subscriptions protocol.MessageNotificationSubscriptions
|
||||
// rng *BrHmacDrbgContext // ???
|
||||
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Public API
|
||||
//
|
||||
|
||||
func New(nodeKey crypto.PrivKey, hostAddr net.Addr, extAddr net.Addr) (*WakuNode, error) {
|
||||
// Creates a Waku Node.
|
||||
if hostAddr == nil {
|
||||
return nil, errors.New("Host address cannot be null")
|
||||
}
|
||||
|
||||
var multiAddresses []ma.Multiaddr
|
||||
hostAddrMA, err := manet.FromNetAddr(hostAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
multiAddresses = append(multiAddresses, hostAddrMA)
|
||||
|
||||
if extAddr != nil {
|
||||
extAddrMA, err := manet.FromNetAddr(extAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
multiAddresses = append(multiAddresses, extAddrMA)
|
||||
}
|
||||
|
||||
opts := []libp2p.Option{
|
||||
libp2p.ListenAddrs(multiAddresses...),
|
||||
libp2p.Identity(nodeKey),
|
||||
libp2p.DefaultTransports, //
|
||||
libp2p.NATPortMap(), // Attempt to open ports using uPNP for NATed hosts.
|
||||
libp2p.DisableRelay(), // TODO: what is this?
|
||||
libp2p.EnableNATService(), // TODO: what is this?
|
||||
}
|
||||
|
||||
// The context governs the lifetime of the libp2p node.
|
||||
// Cancelling it will stop the the host.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
host, err := libp2p.New(ctx, opts...)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w := new(WakuNode)
|
||||
w.peerManager = NewPeerManager(host)
|
||||
w.sw = host
|
||||
w.cancel = cancel
|
||||
// w.filters = new(Filters)
|
||||
|
||||
hostInfo, _ := ma.NewMultiaddr(fmt.Sprintf("/p2p/%s", host.ID().Pretty()))
|
||||
for _, addr := range host.Addrs() {
|
||||
fullAddr := addr.Encapsulate(hostInfo)
|
||||
log.Printf("Listening on %s\n", fullAddr)
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (node *WakuNode) Stop() {
|
||||
// TODO:
|
||||
//if not node.wakuRelay.isNil:
|
||||
// await node.wakuRelay.stop()
|
||||
|
||||
node.cancel()
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
# Waku v2 protocol
|
||||
|
||||
This folder contains implementations of [Waku v2 protocols](https://specs.vac.dev/specs/waku/v2/waku-v2.html).
|
|
@ -0,0 +1,72 @@
|
|||
// The Message Notification system is a method to notify various protocols
|
||||
// running on a node when a new message was received.
|
||||
//
|
||||
// Protocols can subscribe to messages of specific topics, then when one is received
|
||||
// The notification handler function will be called.
|
||||
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type MessageNotificationHandler func(topic string, msg *WakuMessage)
|
||||
|
||||
type MessageNotificationSubscriptionIdentifier string
|
||||
|
||||
type MessageNotificationSubscription struct {
|
||||
topics []string // @TODO TOPIC (?)
|
||||
handler MessageNotificationHandler
|
||||
}
|
||||
|
||||
type MessageNotificationSubscriptions map[string]MessageNotificationSubscription
|
||||
|
||||
func (subscriptions MessageNotificationSubscriptions) subscribe(name string, subscription MessageNotificationSubscription) {
|
||||
subscriptions[name] = subscription
|
||||
}
|
||||
|
||||
func Init(topics []string, handler MessageNotificationHandler) MessageNotificationSubscription {
|
||||
result := MessageNotificationSubscription{}
|
||||
result.topics = topics
|
||||
result.handler = handler
|
||||
return result
|
||||
}
|
||||
|
||||
func containsMatch(lhs []string, rhs []string) bool {
|
||||
for _, l := range lhs {
|
||||
for _, r := range rhs {
|
||||
if l == r {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (subscriptions MessageNotificationSubscriptions) notify(topic string, msg *WakuMessage) {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, subscription := range subscriptions {
|
||||
// @TODO WILL NEED TO CHECK SUBTOPICS IN FUTURE FOR WAKU TOPICS NOT LIBP2P ONES
|
||||
|
||||
found := false
|
||||
for _, subscriptionTopic := range subscription.topics {
|
||||
if subscriptionTopic == topic {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func(subs MessageNotificationSubscription) {
|
||||
subs.handler(topic, msg)
|
||||
wg.Done()
|
||||
}(subscription)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
# Waku Filter protocol
|
||||
|
||||
The filter protocol implements bandwidth preserving filtering for light nodes. See https://github.com/vacp2p/specs/blob/master/specs/waku/v2/waku-store.md for more information.
|
|
@ -0,0 +1,166 @@
|
|||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.25.0-devel
|
||||
// protoc v3.14.0
|
||||
// source: waku_message.proto
|
||||
|
||||
package protocol
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type WakuMessage struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3,oneof" json:"payload,omitempty"`
|
||||
ContentTopic *uint32 `protobuf:"fixed32,2,opt,name=contentTopic,proto3,oneof" json:"contentTopic,omitempty"`
|
||||
Version *uint32 `protobuf:"varint,3,opt,name=version,proto3,oneof" json:"version,omitempty"`
|
||||
}
|
||||
|
||||
func (x *WakuMessage) Reset() {
|
||||
*x = WakuMessage{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_waku_message_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *WakuMessage) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WakuMessage) ProtoMessage() {}
|
||||
|
||||
func (x *WakuMessage) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_waku_message_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WakuMessage.ProtoReflect.Descriptor instead.
|
||||
func (*WakuMessage) Descriptor() ([]byte, []int) {
|
||||
return file_waku_message_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *WakuMessage) GetPayload() []byte {
|
||||
if x != nil {
|
||||
return x.Payload
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *WakuMessage) GetContentTopic() uint32 {
|
||||
if x != nil && x.ContentTopic != nil {
|
||||
return *x.ContentTopic
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WakuMessage) GetVersion() uint32 {
|
||||
if x != nil && x.Version != nil {
|
||||
return *x.Version
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var File_waku_message_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_waku_message_proto_rawDesc = []byte{
|
||||
0x0a, 0x12, 0x77, 0x61, 0x6b, 0x75, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x70,
|
||||
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x9d,
|
||||
0x01, 0x0a, 0x0b, 0x57, 0x61, 0x6b, 0x75, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x1d,
|
||||
0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x48,
|
||||
0x00, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x88, 0x01, 0x01, 0x12, 0x27, 0x0a,
|
||||
0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x6f, 0x70, 0x69, 0x63, 0x18, 0x02, 0x20,
|
||||
0x01, 0x28, 0x07, 0x48, 0x01, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x6f,
|
||||
0x70, 0x69, 0x63, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
|
||||
0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x48, 0x02, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69,
|
||||
0x6f, 0x6e, 0x88, 0x01, 0x01, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61,
|
||||
0x64, 0x42, 0x0f, 0x0a, 0x0d, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x6f, 0x70,
|
||||
0x69, 0x63, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x62, 0x06,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_waku_message_proto_rawDescOnce sync.Once
|
||||
file_waku_message_proto_rawDescData = file_waku_message_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_waku_message_proto_rawDescGZIP() []byte {
|
||||
file_waku_message_proto_rawDescOnce.Do(func() {
|
||||
file_waku_message_proto_rawDescData = protoimpl.X.CompressGZIP(file_waku_message_proto_rawDescData)
|
||||
})
|
||||
return file_waku_message_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_waku_message_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_waku_message_proto_goTypes = []interface{}{
|
||||
(*WakuMessage)(nil), // 0: protocol.WakuMessage
|
||||
}
|
||||
var file_waku_message_proto_depIdxs = []int32{
|
||||
0, // [0:0] is the sub-list for method output_type
|
||||
0, // [0:0] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_waku_message_proto_init() }
|
||||
func file_waku_message_proto_init() {
|
||||
if File_waku_message_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_waku_message_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*WakuMessage); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
file_waku_message_proto_msgTypes[0].OneofWrappers = []interface{}{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_waku_message_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_waku_message_proto_goTypes,
|
||||
DependencyIndexes: file_waku_message_proto_depIdxs,
|
||||
MessageInfos: file_waku_message_proto_msgTypes,
|
||||
}.Build()
|
||||
File_waku_message_proto = out.File
|
||||
file_waku_message_proto_rawDesc = nil
|
||||
file_waku_message_proto_goTypes = nil
|
||||
file_waku_message_proto_depIdxs = nil
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package protocol;
|
||||
|
||||
message WakuMessage {
|
||||
optional bytes payload = 1;
|
||||
optional fixed32 contentTopic = 2;
|
||||
optional uint32 version = 3;
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
# Waku Store protocol
|
||||
|
||||
The store protocol implements historical message support. See https://github.com/vacp2p/specs/blob/master/specs/waku/v2/waku-store.md for more information.
|
|
@ -0,0 +1 @@
|
|||
package waku
|
Loading…
Reference in New Issue