Browse Source

Code clean-up and comments added.

Bernd Fix 3 months ago
parent
commit
b2d49bfb99

+ 10
- 3
src/gnunet/config/config.go View File

@@ -7,9 +7,10 @@ import (
7 7
 	"regexp"
8 8
 	"strings"
9 9
 
10
+	"gnunet/util"
11
+
10 12
 	"github.com/bfix/gospel/crypto/ed25519"
11 13
 	"github.com/bfix/gospel/logger"
12
-	"gnunet/util"
13 14
 )
14 15
 
15 16
 ///////////////////////////////////////////////////////////////////////
@@ -64,6 +65,7 @@ type Config struct {
64 65
 }
65 66
 
66 67
 var (
68
+	// Cfg is the global configuration
67 69
 	Cfg *Config
68 70
 )
69 71
 
@@ -88,6 +90,8 @@ var (
88 90
 	rx = regexp.MustCompile("\\$\\{([^\\}]*)\\}")
89 91
 )
90 92
 
93
+// substString is a helper function to substitute environment variables
94
+// with actual values.
91 95
 func substString(s string, env map[string]string) string {
92 96
 	matches := rx.FindAllStringSubmatch(s, -1)
93 97
 	for _, m := range matches {
@@ -102,7 +106,8 @@ func substString(s string, env map[string]string) string {
102 106
 	return s
103 107
 }
104 108
 
105
-// applySubstitutions
109
+// applySubstitutions traverses the configuration data structure
110
+// and applies string substitutions to all string values.
106 111
 func applySubstitutions(x interface{}, env map[string]string) {
107 112
 
108 113
 	var process func(v reflect.Value)
@@ -140,10 +145,11 @@ func applySubstitutions(x interface{}, env map[string]string) {
140 145
 			}
141 146
 		}
142 147
 	}
143
-
148
+	// start processing at the top-level structure
144 149
 	v := reflect.ValueOf(x)
145 150
 	switch v.Kind() {
146 151
 	case reflect.Ptr:
152
+		// indirect top-level
147 153
 		e := v.Elem()
148 154
 		if e.IsValid() {
149 155
 			process(e)
@@ -151,6 +157,7 @@ func applySubstitutions(x interface{}, env map[string]string) {
151 157
 			logger.Printf(logger.ERROR, "[config] 'nil' pointer encountered")
152 158
 		}
153 159
 	case reflect.Struct:
160
+		// direct top-level
154 161
 		process(v)
155 162
 	}
156 163
 }

+ 21
- 15
src/gnunet/core/peer.go View File

@@ -3,30 +3,25 @@ package core
3 3
 import (
4 4
 	"fmt"
5 5
 
6
-	"github.com/bfix/gospel/crypto/ed25519"
7 6
 	"gnunet/message"
8 7
 	"gnunet/util"
9
-)
10 8
 
11
-/*
12
-type Peer interface {
13
-	GetID() []byte
14
-	GetIDString() string
15
-	GetAddressList() []*util.Address
16
-	Sign(msg []byte) ([]byte, error)
17
-	Verify(msg, sig []byte) bool
18
-}
19
-*/
9
+	"github.com/bfix/gospel/crypto/ed25519"
10
+)
20 11
 
12
+// Peer represents a node in the GNUnet P2P network.
21 13
 type Peer struct {
22
-	pub      *ed25519.PublicKey
23
-	idString string
24
-	addrList []*util.Address
25
-	prv      *ed25519.PrivateKey      // long-term signing key
14
+	prv      *ed25519.PrivateKey      // node private key (long-term signing key)
15
+	pub      *ed25519.PublicKey       // node public key (=identifier)
16
+	idString string                   // node identifier as string
17
+	addrList []*util.Address          // list of addresses associated with node
26 18
 	ephPrv   *ed25519.PrivateKey      // ephemeral signing key
27 19
 	ephMsg   *message.EphemeralKeyMsg // ephemeral signing key message
28 20
 }
29 21
 
22
+// NewPeer instantiates a new peer object from given data. If a local peer
23
+// is created, the data is the seed for generating the private key of the node;
24
+// for a remote peer the data is the binary representation of its public key.
30 25
 func NewPeer(data []byte, local bool) (p *Peer, err error) {
31 26
 	p = new(Peer)
32 27
 	if local {
@@ -45,42 +40,52 @@ func NewPeer(data []byte, local bool) (p *Peer, err error) {
45 40
 	return
46 41
 }
47 42
 
43
+// EphKeyMsg returns a new initialized message to negotiate session keys.
48 44
 func (p *Peer) EphKeyMsg() *message.EphemeralKeyMsg {
49 45
 	return p.ephMsg
50 46
 }
51 47
 
48
+// SetEphKeyMsg saves a template for new key negotiation messages.
52 49
 func (p *Peer) SetEphKeyMsg(msg *message.EphemeralKeyMsg) {
53 50
 	p.ephMsg = msg
54 51
 }
55 52
 
53
+// EphPrvKey returns the current ephemeral private key.
56 54
 func (p *Peer) EphPrvKey() *ed25519.PrivateKey {
57 55
 	return p.ephPrv
58 56
 }
59 57
 
58
+// PrvKey return the private key of the node.
60 59
 func (p *Peer) PrvKey() *ed25519.PrivateKey {
61 60
 	return p.prv
62 61
 }
63 62
 
63
+// PubKey return the public key of the node.
64 64
 func (p *Peer) PubKey() *ed25519.PublicKey {
65 65
 	return p.pub
66 66
 }
67 67
 
68
+// GetID returns the node ID (public key) in binary format
68 69
 func (p *Peer) GetID() []byte {
69 70
 	return p.pub.Bytes()
70 71
 }
71 72
 
73
+// GetIDString returns the string representation of the public key of the node.
72 74
 func (p *Peer) GetIDString() string {
73 75
 	return p.idString
74 76
 }
75 77
 
78
+// GetAddressList returns a list of addresses associated with this peer.
76 79
 func (p *Peer) GetAddressList() []*util.Address {
77 80
 	return p.addrList
78 81
 }
79 82
 
83
+// AddAddress adds a new address for a node.
80 84
 func (p *Peer) AddAddress(a *util.Address) {
81 85
 	p.addrList = append(p.addrList, a)
82 86
 }
83 87
 
88
+// Sign a message with the (long-term) private key.
84 89
 func (p *Peer) Sign(msg []byte) (*ed25519.EdSignature, error) {
85 90
 	if p.prv == nil {
86 91
 		return nil, fmt.Errorf("No private key")
@@ -88,6 +93,7 @@ func (p *Peer) Sign(msg []byte) (*ed25519.EdSignature, error) {
88 93
 	return p.prv.EdSign(msg)
89 94
 }
90 95
 
96
+// Verify a message signature with the public key of a peer.
91 97
 func (p *Peer) Verify(msg []byte, sig *ed25519.EdSignature) (bool, error) {
92 98
 	return p.pub.EdVerify(msg, sig)
93 99
 }

+ 3
- 0
src/gnunet/crypto/hash.go View File

@@ -6,16 +6,19 @@ import (
6 6
 	"gnunet/util"
7 7
 )
8 8
 
9
+// HashCode is the result of a 512-bit hash function (SHA-512)
9 10
 type HashCode struct {
10 11
 	Bits []byte `size:"64"`
11 12
 }
12 13
 
14
+// NewHashCode creates a new, uninitalized hash value
13 15
 func NewHashCode() *HashCode {
14 16
 	return &HashCode{
15 17
 		Bits: make([]byte, 64),
16 18
 	}
17 19
 }
18 20
 
21
+// Hash returns the SHA-512 hash value of a given blob
19 22
 func Hash(data []byte) *HashCode {
20 23
 	val := sha512.Sum512(data)
21 24
 	return &HashCode{

+ 1
- 0
src/gnunet/crypto/key_derivation.go View File

@@ -9,6 +9,7 @@ import (
9 9
 	"golang.org/x/crypto/hkdf"
10 10
 )
11 11
 
12
+// Curve parameters
12 13
 var (
13 14
 	ED25519_N = ed25519.GetCurve().N
14 15
 )

+ 2
- 2
src/gnunet/crypto/key_exchange.go View File

@@ -4,8 +4,8 @@ import (
4 4
 	"github.com/bfix/gospel/crypto/ed25519"
5 5
 )
6 6
 
7
-// SharedSecret computes a 64 byte shared secret
8
-// between (prvA,pubB) and (prvB,pubA).
7
+// SharedSecret computes a 64 byte shared secret between (prvA,pubB)
8
+// and (prvB,pubA) by a Diffie-Hellman-like scheme.
9 9
 func SharedSecret(prv *ed25519.PrivateKey, pub *ed25519.PublicKey) *HashCode {
10 10
 	ss := pub.Mult(prv.D).Q.X().Bytes()
11 11
 	return Hash(ss)

+ 1
- 0
src/gnunet/crypto/signature.go View File

@@ -1,5 +1,6 @@
1 1
 package crypto
2 2
 
3
+// SignaturePurpose is the GNUnet data structure used as header for signed data.
3 4
 type SignaturePurpose struct {
4 5
 	Size    uint32 `order:"big"` // How many bytes are signed?
5 6
 	Purpose uint32 `order:"big"` // Signature purpose

+ 15
- 4
src/gnunet/crypto/symmetric.go View File

@@ -8,11 +8,17 @@ import (
8 8
 	"golang.org/x/crypto/twofish"
9 9
 )
10 10
 
11
+// Symmetric encryption in GNUnet uses a two-layer scheme:
12
+// * Encryption: OUT = twofish_cfb(aes_cfb(IN))
13
+// * Decryption: OUT = aes_cfb(twofish_cfb(IN))
14
+
15
+// SymmetricKey is a key for the GNUnet-specific two-layer encryption scheme.
11 16
 type SymmetricKey struct {
12
-	AESKey     []byte `size:"32"`
13
-	TwofishKey []byte `size:"32"`
17
+	AESKey     []byte `size:"32"` // key for AES-CFB
18
+	TwofishKey []byte `size:"32"` // key for Twofish-CFB
14 19
 }
15 20
 
21
+// NewSymmetricKey generates a new (random) symmetric key.
16 22
 func NewSymmetricKey() *SymmetricKey {
17 23
 	skey := &SymmetricKey{
18 24
 		AESKey:     make([]byte, 32),
@@ -23,11 +29,14 @@ func NewSymmetricKey() *SymmetricKey {
23 29
 	return skey
24 30
 }
25 31
 
32
+// SymmetricIV is an initialization vector for the GNUnet-specific two-layer
33
+// encryption scheme.
26 34
 type SymmetricIV struct {
27
-	AESIv     []byte `size:"16"`
28
-	TwofishIv []byte `size:"16"`
35
+	AESIv     []byte `size:"16"` // IV for AES-CFB
36
+	TwofishIv []byte `size:"16"` // IV for Twofish-CFB
29 37
 }
30 38
 
39
+// NewSymmetricIV generates a new (random) initialization vector.
31 40
 func NewSymmetricIV() *SymmetricIV {
32 41
 	iv := &SymmetricIV{
33 42
 		AESIv:     make([]byte, 16),
@@ -38,6 +47,7 @@ func NewSymmetricIV() *SymmetricIV {
38 47
 	return iv
39 48
 }
40 49
 
50
+// SymmetricDecrypt decrypts the data with given key and initialization vector.
41 51
 func SymmetricDecrypt(data []byte, skey *SymmetricKey, iv *SymmetricIV) ([]byte, error) {
42 52
 	// Decrypt with Twofish CFB stream cipher
43 53
 	tf, err := twofish.NewCipher(skey.TwofishKey)
@@ -58,6 +68,7 @@ func SymmetricDecrypt(data []byte, skey *SymmetricKey, iv *SymmetricIV) ([]byte,
58 68
 	return out, nil
59 69
 }
60 70
 
71
+// SymmetricEncrypt encrypts the data with given key and initialization vector.
61 72
 func SymmetricEncrypt(data []byte, skey *SymmetricKey, iv *SymmetricIV) ([]byte, error) {
62 73
 	// Encrypt with AES CFB stream cipher
63 74
 	aes, err := aes.NewCipher(skey.AESKey)

+ 0
- 22
src/gnunet/enums/block.go View File

@@ -1,22 +0,0 @@
1
-package enums
2
-
3
-var (
4
-	BLOCK_TYPE_ANY            = 0  // Any type of block, used as a wildcard when searching.
5
-	BLOCK_TYPE_FS_DBLOCK      = 1  // Data block (leaf) in the CHK tree.
6
-	BLOCK_TYPE_FS_IBLOCK      = 2  // Inner block in the CHK tree.
7
-	BLOCK_TYPE_FS_KBLOCK      = 3  // Legacy type, no longer in use.
8
-	BLOCK_TYPE_FS_SBLOCK      = 4  // Legacy type, no longer in use.
9
-	BLOCK_TYPE_FS_NBLOCK      = 5  // Legacy type, no longer in use.
10
-	BLOCK_TYPE_FS_ONDEMAND    = 6  // Type of a block representing a block to be encoded on demand from disk.
11
-	BLOCK_TYPE_DHT_HELLO      = 7  // Type of a block that contains a HELLO for a peer
12
-	BLOCK_TYPE_TEST           = 8  // Block for testing.
13
-	BLOCK_TYPE_FS_UBLOCK      = 9  // Type of a block representing any type of search result (universal).
14
-	BLOCK_TYPE_DNS            = 10 // Block for storing DNS exit service advertisements.
15
-	BLOCK_TYPE_GNS_NAMERECORD = 11 // Block for storing record data
16
-	BLOCK_TYPE_REVOCATION     = 12 // Block type for a revocation message by which a key is revoked.
17
-
18
-	BLOCK_TYPE_REGEX             = 22 // Block to store a cadet regex state
19
-	BLOCK_TYPE_REGEX_ACCEPT      = 23 // Block to store a cadet regex accepting state
20
-	BLOCK_TYPE_SET_TEST          = 24 // Block for testing set/consensus.
21
-	BLOCK_TYPE_CONSENSUS_ELEMENT = 25 // Block type for consensus elements.
22
-)

+ 23
- 0
src/gnunet/enums/dht.go View File

@@ -1,5 +1,6 @@
1 1
 package enums
2 2
 
3
+// DHT flags and settings
3 4
 var (
4 5
 	DHT_RO_NONE                   = 0  // Default.  Do nothing special.
5 6
 	DHT_RO_DEMULTIPLEX_EVERYWHERE = 1  // Each peer along the way should look at 'enc'
@@ -10,3 +11,25 @@ var (
10 11
 
11 12
 	DHT_GNS_REPLICATION_LEVEL = 10
12 13
 )
14
+
15
+// DHT block types
16
+var (
17
+	BLOCK_TYPE_ANY            = 0  // Any type of block, used as a wildcard when searching.
18
+	BLOCK_TYPE_FS_DBLOCK      = 1  // Data block (leaf) in the CHK tree.
19
+	BLOCK_TYPE_FS_IBLOCK      = 2  // Inner block in the CHK tree.
20
+	BLOCK_TYPE_FS_KBLOCK      = 3  // Legacy type, no longer in use.
21
+	BLOCK_TYPE_FS_SBLOCK      = 4  // Legacy type, no longer in use.
22
+	BLOCK_TYPE_FS_NBLOCK      = 5  // Legacy type, no longer in use.
23
+	BLOCK_TYPE_FS_ONDEMAND    = 6  // Type of a block representing a block to be encoded on demand from disk.
24
+	BLOCK_TYPE_DHT_HELLO      = 7  // Type of a block that contains a HELLO for a peer
25
+	BLOCK_TYPE_TEST           = 8  // Block for testing.
26
+	BLOCK_TYPE_FS_UBLOCK      = 9  // Type of a block representing any type of search result (universal).
27
+	BLOCK_TYPE_DNS            = 10 // Block for storing DNS exit service advertisements.
28
+	BLOCK_TYPE_GNS_NAMERECORD = 11 // Block for storing record data
29
+	BLOCK_TYPE_REVOCATION     = 12 // Block type for a revocation message by which a key is revoked.
30
+
31
+	BLOCK_TYPE_REGEX             = 22 // Block to store a cadet regex state
32
+	BLOCK_TYPE_REGEX_ACCEPT      = 23 // Block to store a cadet regex accepting state
33
+	BLOCK_TYPE_SET_TEST          = 24 // Block for testing set/consensus.
34
+	BLOCK_TYPE_CONSENSUS_ELEMENT = 25 // Block type for consensus elements.
35
+)

+ 1
- 0
src/gnunet/enums/gns.go View File

@@ -1,5 +1,6 @@
1 1
 package enums
2 2
 
3
+// GNS constants
3 4
 var (
4 5
 	GNS_MAX_BLOCK_SIZE = (63 * 1024) // Maximum size of a value that can be stored in a GNS block.
5 6
 

+ 8
- 0
src/gnunet/message/message.go View File

@@ -6,27 +6,35 @@ import (
6 6
 	"github.com/bfix/gospel/data"
7 7
 )
8 8
 
9
+// Error codes
9 10
 var (
10 11
 	ErrMsgHeaderTooSmall = errors.New("Message header too small")
11 12
 )
12 13
 
14
+// Message is an interface for all GNUnet-specific messages.
13 15
 type Message interface {
14 16
 	Header() *MessageHeader
15 17
 }
16 18
 
19
+// MessageHeader encapsulates the common part of all GNUnet messages (at the
20
+// beginning of the data).
17 21
 type MessageHeader struct {
18 22
 	MsgSize uint16 `order:"big"`
19 23
 	MsgType uint16 `order:"big"`
20 24
 }
21 25
 
26
+// Size returns the total size of the message (header + body)
22 27
 func (mh *MessageHeader) Size() uint16 {
23 28
 	return mh.MsgSize
24 29
 }
25 30
 
31
+// Type returns the message type (defines the layout of the body data)
26 32
 func (mh *MessageHeader) Type() uint16 {
27 33
 	return mh.MsgType
28 34
 }
29 35
 
36
+// GetMsgHeader returns the header of a message from a byte array (as the
37
+// serialized form).
30 38
 func GetMsgHeader(b []byte) (mh *MessageHeader, err error) {
31 39
 	if b == nil || len(b) < 4 {
32 40
 		return nil, ErrMsgHeaderTooSmall

+ 23
- 10
src/gnunet/message/msg_core.go View File

@@ -5,21 +5,25 @@ import (
5 5
 	"fmt"
6 6
 	"time"
7 7
 
8
-	"github.com/bfix/gospel/crypto/ed25519"
9
-	"github.com/bfix/gospel/data"
8
+	"gnunet/crypto"
10 9
 	"gnunet/enums"
11 10
 	"gnunet/util"
11
+
12
+	"github.com/bfix/gospel/crypto/ed25519"
13
+	"github.com/bfix/gospel/data"
12 14
 )
13 15
 
16
+// EphKeyBlock defines the layout of signed ephemeral key with attributes.
14 17
 type EphKeyBlock struct {
15
-	SignSize     uint32            `order:"big"` // length of signed block
16
-	SigPurpose   uint32            `order:"big"` // signature purpose: SIG_ECC_KEY
17
-	CreateTime   util.AbsoluteTime // Time of key creation
18
-	ExpireTime   util.RelativeTime // Time to live for key
19
-	EphemeralKey []byte            `size:"32"` // Ephemeral EdDSA public key
20
-	PeerID       *util.PeerID      // Peer identity (EdDSA public key)
18
+	Purpose      *crypto.SignaturePurpose // signature purpose: SIG_ECC_KEY
19
+	CreateTime   util.AbsoluteTime        // Time of key creation
20
+	ExpireTime   util.RelativeTime        // Time to live for key
21
+	EphemeralKey []byte                   `size:"32"` // Ephemeral EdDSA public key
22
+	PeerID       *util.PeerID             // Peer identity (EdDSA public key)
21 23
 }
22 24
 
25
+// EphemeralKeyMsg announces a new transient key for a peer. The key is signed
26
+// by the issuing peer.
23 27
 type EphemeralKeyMsg struct {
24 28
 	MsgSize      uint16 `order:"big"` // total size of message
25 29
 	MsgType      uint16 `order:"big"` // CORE_EPHEMERAL_KEY (88)
@@ -28,6 +32,7 @@ type EphemeralKeyMsg struct {
28 32
 	SignedBlock  *EphKeyBlock
29 33
 }
30 34
 
35
+// NewEphemeralKeyMsg creates an empty message for key announcement.
31 36
 func NewEphemeralKeyMsg() *EphemeralKeyMsg {
32 37
 	return &EphemeralKeyMsg{
33 38
 		MsgSize:      160,
@@ -35,8 +40,10 @@ func NewEphemeralKeyMsg() *EphemeralKeyMsg {
35 40
 		SenderStatus: 1,
36 41
 		Signature:    make([]byte, 64),
37 42
 		SignedBlock: &EphKeyBlock{
38
-			SignSize:     88,
39
-			SigPurpose:   enums.SIG_ECC_KEY,
43
+			Purpose: &crypto.SignaturePurpose{
44
+				Size:    88,
45
+				Purpose: enums.SIG_ECC_KEY,
46
+			},
40 47
 			CreateTime:   util.AbsoluteTimeNow(),
41 48
 			ExpireTime:   util.NewRelativeTime(12 * time.Hour),
42 49
 			EphemeralKey: make([]byte, 32),
@@ -45,6 +52,7 @@ func NewEphemeralKeyMsg() *EphemeralKeyMsg {
45 52
 	}
46 53
 }
47 54
 
55
+// String returns a human-readable representation of the message.
48 56
 func (m *EphemeralKeyMsg) String() string {
49 57
 	return fmt.Sprintf("EphKeyMsg{peer=%s,ephkey=%s,create=%s,expire=%s,status=%d}",
50 58
 		util.EncodeBinaryToString(m.SignedBlock.PeerID.Key),
@@ -58,10 +66,13 @@ func (msg *EphemeralKeyMsg) Header() *MessageHeader {
58 66
 	return &MessageHeader{msg.MsgSize, msg.MsgType}
59 67
 }
60 68
 
69
+// Public extracts the public key of an announcing peer.
61 70
 func (m *EphemeralKeyMsg) Public() *ed25519.PublicKey {
62 71
 	return ed25519.NewPublicKeyFromBytes(m.SignedBlock.PeerID.Key)
63 72
 }
64 73
 
74
+// Verify the integrity of the message data using the public key of the
75
+// announcing peer.
65 76
 func (m *EphemeralKeyMsg) Verify(pub *ed25519.PublicKey) (bool, error) {
66 77
 	data, err := data.Marshal(m.SignedBlock)
67 78
 	if err != nil {
@@ -74,6 +85,8 @@ func (m *EphemeralKeyMsg) Verify(pub *ed25519.PublicKey) (bool, error) {
74 85
 	return pub.EdVerify(data, sig)
75 86
 }
76 87
 
88
+// NewEphemeralKey creates a new ephemeral key signed by a long-term private
89
+// key and the corresponding GNUnet message to announce the new key.
77 90
 func NewEphemeralKey(peerId []byte, ltPrv *ed25519.PrivateKey) (*ed25519.PrivateKey, *EphemeralKeyMsg, error) {
78 91
 	msg := NewEphemeralKeyMsg()
79 92
 	copy(msg.SignedBlock.PeerID.Key, peerId)

+ 2
- 0
src/gnunet/message/msg_dht.go View File

@@ -51,6 +51,7 @@ func (m *DHTClientGetMsg) SetXQuery(xq []byte) []byte {
51 51
 	return prev
52 52
 }
53 53
 
54
+// String returns a human-readable representation of the message.
54 55
 func (m *DHTClientGetMsg) String() string {
55 56
 	return fmt.Sprintf("DHTClientGetMsg{Id:%d,Type=%d,Options=%d,Repl=%d,Key=%s}",
56 57
 		m.Id, m.Type, m.Options, m.ReplLevel, hex.EncodeToString(m.Key.Bits))
@@ -98,6 +99,7 @@ func NewDHTClientResultMsg(key *crypto.HashCode) *DHTClientResultMsg {
98 99
 	}
99 100
 }
100 101
 
102
+// String returns a human-readable representation of the message.
101 103
 func (m *DHTClientResultMsg) String() string {
102 104
 	return fmt.Sprintf("DHTClientResultMsg{id:%d,expire=%s}", m.Id, m.Expire)
103 105
 }

+ 10
- 6
src/gnunet/message/msg_gns.go View File

@@ -3,9 +3,10 @@ package message
3 3
 import (
4 4
 	"fmt"
5 5
 
6
-	"github.com/bfix/gospel/logger"
7 6
 	"gnunet/enums"
8 7
 	"gnunet/util"
8
+
9
+	"github.com/bfix/gospel/logger"
9 10
 )
10 11
 
11 12
 //----------------------------------------------------------------------
@@ -38,13 +39,13 @@ func NewGNSLookupMsg() *GNSLookupMsg {
38 39
 	}
39 40
 }
40 41
 
41
-// SetName
42
+// SetName appends the name to lookup to the message
42 43
 func (m *GNSLookupMsg) SetName(name string) {
43 44
 	m.Name = util.Clone(append([]byte(name), 0))
44 45
 	m.MsgSize = uint16(48 + len(m.Name))
45 46
 }
46 47
 
47
-// GetName
48
+// GetName returns the name to lookup from the message
48 49
 func (m *GNSLookupMsg) GetName() string {
49 50
 	size := len(m.Name)
50 51
 	if m.Name[size-1] != 0 {
@@ -55,7 +56,7 @@ func (m *GNSLookupMsg) GetName() string {
55 56
 	return string(m.Name[:size])
56 57
 }
57 58
 
58
-// String
59
+// String returns a human-readable representation of the message.
59 60
 func (m *GNSLookupMsg) String() string {
60 61
 	return fmt.Sprintf(
61 62
 		"GNSLookupMsg{Id=%d,Zone=%s,Options=%d,Type=%d,Name=%s}",
@@ -72,6 +73,8 @@ func (msg *GNSLookupMsg) Header() *MessageHeader {
72 73
 // GNS_LOOKUP_RESULT
73 74
 //----------------------------------------------------------------------
74 75
 
76
+// GNSResourceRecord is the GNUnet-specific representation of resource
77
+// records (not to be confused with DNS resource records).
75 78
 type GNSResourceRecord struct {
76 79
 	Expires util.AbsoluteTime // Expiration time for the record
77 80
 	Size    uint32            `order:"big"` // Number of bytes in 'Data'
@@ -80,6 +83,7 @@ type GNSResourceRecord struct {
80 83
 	Data    []byte            `size:"Size"` // Record data
81 84
 }
82 85
 
86
+// String returns a human-readable representation of the message.
83 87
 func (r *GNSResourceRecord) String() string {
84 88
 	return fmt.Sprintf("GNSResourceRecord{type=%s,expire=%s,flags=%d,size=%d}",
85 89
 		enums.GNS_TYPE[int(r.Type)], r.Expires, r.Flags, r.Size)
@@ -105,7 +109,7 @@ func NewGNSLookupResultMsg(id uint32) *GNSLookupResultMsg {
105 109
 	}
106 110
 }
107 111
 
108
-// AddRecord
112
+// AddRecord adds a GNS resource recordto the response message.
109 113
 func (m *GNSLookupResultMsg) AddRecord(rec *GNSResourceRecord) error {
110 114
 	recSize := 20 + int(rec.Size)
111 115
 	if int(m.MsgSize)+recSize > enums.GNS_MAX_BLOCK_SIZE {
@@ -117,7 +121,7 @@ func (m *GNSLookupResultMsg) AddRecord(rec *GNSResourceRecord) error {
117 121
 	return nil
118 122
 }
119 123
 
120
-// String
124
+// String returns a human-readable representation of the message.
121 125
 func (m *GNSLookupResultMsg) String() string {
122 126
 	return fmt.Sprintf("GNSLookupResultMsg{Id=%d,Count=%d}", m.Id, m.Count)
123 127
 }

+ 2
- 2
src/gnunet/message/msg_namecache.go View File

@@ -33,7 +33,7 @@ func NewNamecacheLookupMsg(query *crypto.HashCode) *NamecacheLookupMsg {
33 33
 	}
34 34
 }
35 35
 
36
-// String
36
+// String returns a human-readable representation of the message.
37 37
 func (m *NamecacheLookupMsg) String() string {
38 38
 	return fmt.Sprintf("NamecacheLookupMsg{Id=%d,Query=%s}",
39 39
 		m.Id, hex.EncodeToString(m.Query.Bits))
@@ -72,7 +72,7 @@ func NewNamecacheLookupResultMsg() *NamecacheLookupResultMsg {
72 72
 	}
73 73
 }
74 74
 
75
-// String
75
+// String returns a human-readable representation of the message.
76 76
 func (m *NamecacheLookupResultMsg) String() string {
77 77
 	return fmt.Sprintf("NamecacheLookupResultMsg{id=%d,expire=%s}",
78 78
 		m.Id, m.Expire)

+ 125
- 82
src/gnunet/message/msg_transport.go View File

@@ -4,22 +4,26 @@ import (
4 4
 	"fmt"
5 5
 	"time"
6 6
 
7
-	"github.com/bfix/gospel/crypto/ed25519"
8
-	"github.com/bfix/gospel/data"
7
+	"gnunet/crypto"
9 8
 	"gnunet/enums"
10 9
 	"gnunet/util"
10
+
11
+	"github.com/bfix/gospel/crypto/ed25519"
12
+	"github.com/bfix/gospel/data"
11 13
 )
12 14
 
13 15
 //----------------------------------------------------------------------
14 16
 // TRANSPORT_TCP_WELCOME
15 17
 //----------------------------------------------------------------------
16 18
 
19
+// TransportTcpWelcomeMsg
17 20
 type TransportTcpWelcomeMsg struct {
18 21
 	MsgSize uint16       `order:"big"` // total size of message
19 22
 	MsgType uint16       `order:"big"` // TRANSPORT_TCP_WELCOME (61)
20 23
 	PeerID  *util.PeerID // Peer identity (EdDSA public key)
21 24
 }
22 25
 
26
+// NewTransportTcpWelcomeMsg creates a new message for a given peer.
23 27
 func NewTransportTcpWelcomeMsg(peerid *util.PeerID) *TransportTcpWelcomeMsg {
24 28
 	if peerid == nil {
25 29
 		peerid = util.NewPeerID(nil)
@@ -31,6 +35,7 @@ func NewTransportTcpWelcomeMsg(peerid *util.PeerID) *TransportTcpWelcomeMsg {
31 35
 	}
32 36
 }
33 37
 
38
+// String returns a human-readable representation of the message.
34 39
 func (m *TransportTcpWelcomeMsg) String() string {
35 40
 	return fmt.Sprintf("TransportTcpWelcomeMsg{peer=%s}", m.PeerID)
36 41
 }
@@ -41,6 +46,59 @@ func (msg *TransportTcpWelcomeMsg) Header() *MessageHeader {
41 46
 }
42 47
 
43 48
 //----------------------------------------------------------------------
49
+// TRANSPORT_PING
50
+//
51
+// Message used to ask a peer to validate receipt (to check an address
52
+// from a HELLO).  Followed by the address we are trying to validate,
53
+// or an empty address if we are just sending a PING to confirm that a
54
+// connection which the receiver (of the PING) initiated is still valid.
55
+//----------------------------------------------------------------------
56
+
57
+// TransportPingMsg
58
+type TransportPingMsg struct {
59
+	MsgSize   uint16       `order:"big"` // total size of message
60
+	MsgType   uint16       `order:"big"` // TRANSPORT_PING (372)
61
+	Challenge uint32       // Challenge code (to ensure fresh reply)
62
+	Target    *util.PeerID // EdDSA public key (long-term) of target peer
63
+	Address   []byte       `size:"*"` // encoded address
64
+}
65
+
66
+// TransportPingMsg creates a new message for given peer with an address to
67
+// be validated.
68
+func NewTransportPingMsg(target *util.PeerID, a *util.Address) *TransportPingMsg {
69
+	if target == nil {
70
+		target = util.NewPeerID(nil)
71
+	}
72
+	m := &TransportPingMsg{
73
+		MsgSize:   uint16(40),
74
+		MsgType:   TRANSPORT_PING,
75
+		Challenge: util.RndUInt32(),
76
+		Target:    target,
77
+		Address:   nil,
78
+	}
79
+	if a != nil {
80
+		if addrData, err := data.Marshal(a); err == nil {
81
+			m.Address = addrData
82
+			m.MsgSize += uint16(len(addrData))
83
+		}
84
+	}
85
+	return m
86
+}
87
+
88
+// String returns a human-readable representation of the message.
89
+func (m *TransportPingMsg) String() string {
90
+	a := new(util.Address)
91
+	data.Unmarshal(a, m.Address)
92
+	return fmt.Sprintf("TransportPingMsg{target=%s,addr=%s,challenge=%d}",
93
+		m.Target, a, m.Challenge)
94
+}
95
+
96
+// Header returns the message header in a separate instance.
97
+func (msg *TransportPingMsg) Header() *MessageHeader {
98
+	return &MessageHeader{msg.MsgSize, msg.MsgType}
99
+}
100
+
101
+//----------------------------------------------------------------------
44 102
 // TRANSPORT_PONG
45 103
 //
46 104
 // Message used to validate a HELLO.  The challenge is included in the
@@ -53,29 +111,33 @@ func (msg *TransportTcpWelcomeMsg) Header() *MessageHeader {
53 111
 // a connection that we initiated).
54 112
 //----------------------------------------------------------------------
55 113
 
114
+// SignedAddress is the signed block of data representing a node address
56 115
 type SignedAddress struct {
57
-	SignLength uint32            `order:"big"` // Length of signed block
58
-	Purpose    uint32            `order:"big"` // SIG_TRANSPORT_PONG_OWN
59
-	ExpireOn   util.AbsoluteTime // usec epoch
60
-	AddrSize   uint32            `order:"big"`     // size of address
61
-	Address    []byte            `size:"AddrSize"` // address
116
+	Purpose  *crypto.SignaturePurpose // SIG_TRANSPORT_PONG_OWN
117
+	ExpireOn util.AbsoluteTime        // usec epoch
118
+	AddrSize uint32                   `order:"big"`     // size of address
119
+	Address  []byte                   `size:"AddrSize"` // address
62 120
 }
63 121
 
122
+// NewSignedAddress creates a new (signable) data block from an address.
64 123
 func NewSignedAddress(a *util.Address) *SignedAddress {
65 124
 	// serialize address
66 125
 	addrData, _ := data.Marshal(a)
67 126
 	alen := len(addrData)
68 127
 	addr := &SignedAddress{
69
-		SignLength: uint32(alen + 20),
70
-		Purpose:    enums.SIG_TRANSPORT_PONG_OWN,
71
-		ExpireOn:   util.AbsoluteTimeNow().Add(12 * time.Hour),
72
-		AddrSize:   uint32(alen),
73
-		Address:    make([]byte, alen),
128
+		Purpose: &crypto.SignaturePurpose{
129
+			Size:    uint32(alen + 20),
130
+			Purpose: enums.SIG_TRANSPORT_PONG_OWN,
131
+		},
132
+		ExpireOn: util.AbsoluteTimeNow().Add(12 * time.Hour),
133
+		AddrSize: uint32(alen),
134
+		Address:  make([]byte, alen),
74 135
 	}
75 136
 	copy(addr.Address, addrData)
76 137
 	return addr
77 138
 }
78 139
 
140
+// TransportPongMsg
79 141
 type TransportPongMsg struct {
80 142
 	MsgSize     uint16         `order:"big"` // total size of message
81 143
 	MsgType     uint16         `order:"big"` // TRANSPORT_PING (372)
@@ -84,6 +146,8 @@ type TransportPongMsg struct {
84 146
 	SignedBlock *SignedAddress // signed block of data
85 147
 }
86 148
 
149
+// NewTransportPongMsg creates a reponse message with an address the replying
150
+// peer wants to be reached.
87 151
 func NewTransportPongMsg(challenge uint32, a *util.Address) *TransportPongMsg {
88 152
 	m := &TransportPongMsg{
89 153
 		MsgSize:     72,
@@ -94,12 +158,13 @@ func NewTransportPongMsg(challenge uint32, a *util.Address) *TransportPongMsg {
94 158
 	}
95 159
 	if a != nil {
96 160
 		sa := NewSignedAddress(a)
97
-		m.MsgSize += uint16(sa.SignLength)
161
+		m.MsgSize += uint16(sa.Purpose.Size)
98 162
 		m.SignedBlock = sa
99 163
 	}
100 164
 	return m
101 165
 }
102 166
 
167
+// String returns a human-readable representation of the message.
103 168
 func (m *TransportPongMsg) String() string {
104 169
 	a := new(util.Address)
105 170
 	if err := data.Unmarshal(a, m.SignedBlock.Address); err == nil {
@@ -114,6 +179,7 @@ func (msg *TransportPongMsg) Header() *MessageHeader {
114 179
 	return &MessageHeader{msg.MsgSize, msg.MsgType}
115 180
 }
116 181
 
182
+// Sign the address block of a pong message.
117 183
 func (m *TransportPongMsg) Sign(prv *ed25519.PrivateKey) error {
118 184
 	data, err := data.Marshal(m.SignedBlock)
119 185
 	if err != nil {
@@ -127,6 +193,7 @@ func (m *TransportPongMsg) Sign(prv *ed25519.PrivateKey) error {
127 193
 	return nil
128 194
 }
129 195
 
196
+// Verify the address block of a pong message
130 197
 func (m *TransportPongMsg) Verify(pub *ed25519.PublicKey) (bool, error) {
131 198
 	data, err := data.Marshal(m.SignedBlock)
132 199
 	if err != nil {
@@ -140,55 +207,6 @@ func (m *TransportPongMsg) Verify(pub *ed25519.PublicKey) (bool, error) {
140 207
 }
141 208
 
142 209
 //----------------------------------------------------------------------
143
-// TRANSPORT_PING
144
-//
145
-// Message used to ask a peer to validate receipt (to check an address
146
-// from a HELLO).  Followed by the address we are trying to validate,
147
-// or an empty address if we are just sending a PING to confirm that a
148
-// connection which the receiver (of the PING) initiated is still valid.
149
-//----------------------------------------------------------------------
150
-
151
-type TransportPingMsg struct {
152
-	MsgSize   uint16       `order:"big"` // total size of message
153
-	MsgType   uint16       `order:"big"` // TRANSPORT_PING (372)
154
-	Challenge uint32       // Challenge code (to ensure fresh reply)
155
-	Target    *util.PeerID // EdDSA public key (long-term) of target peer
156
-	Address   []byte       `size:"*"` // encoded address
157
-}
158
-
159
-func NewTransportPingMsg(target *util.PeerID, a *util.Address) *TransportPingMsg {
160
-	if target == nil {
161
-		target = util.NewPeerID(nil)
162
-	}
163
-	m := &TransportPingMsg{
164
-		MsgSize:   uint16(40),
165
-		MsgType:   TRANSPORT_PING,
166
-		Challenge: util.RndUInt32(),
167
-		Target:    target,
168
-		Address:   nil,
169
-	}
170
-	if a != nil {
171
-		if addrData, err := data.Marshal(a); err == nil {
172
-			m.Address = addrData
173
-			m.MsgSize += uint16(len(addrData))
174
-		}
175
-	}
176
-	return m
177
-}
178
-
179
-func (m *TransportPingMsg) String() string {
180
-	a := new(util.Address)
181
-	data.Unmarshal(a, m.Address)
182
-	return fmt.Sprintf("TransportPingMsg{target=%s,addr=%s,challenge=%d}",
183
-		m.Target, a, m.Challenge)
184
-}
185
-
186
-// Header returns the message header in a separate instance.
187
-func (msg *TransportPingMsg) Header() *MessageHeader {
188
-	return &MessageHeader{msg.MsgSize, msg.MsgType}
189
-}
190
-
191
-//----------------------------------------------------------------------
192 210
 // HELLO
193 211
 //
194 212
 // A HELLO message is used to exchange information about
@@ -202,6 +220,7 @@ func (msg *TransportPingMsg) Header() *MessageHeader {
202 220
 // 4) address (address-length bytes)
203 221
 //----------------------------------------------------------------------
204 222
 
223
+// HelloAddress
205 224
 type HelloAddress struct {
206 225
 	Transport string            // Name of transport
207 226
 	AddrSize  uint16            `order:"big"` // Size of address entry
@@ -209,6 +228,7 @@ type HelloAddress struct {
209 228
 	Address   []byte            `size:"AddrSize"` // Address specification
210 229
 }
211 230
 
231
+// NewHelloAddress create a new HELLO address from the given address
212 232
 func NewAddress(a *util.Address) *HelloAddress {
213 233
 	addr := &HelloAddress{
214 234
 		Transport: a.Transport,
@@ -220,11 +240,13 @@ func NewAddress(a *util.Address) *HelloAddress {
220 240
 	return addr
221 241
 }
222 242
 
243
+// String returns a human-readable representation of the message.
223 244
 func (a *HelloAddress) String() string {
224 245
 	return fmt.Sprintf("Address{%s,expire=%s}",
225 246
 		util.AddressString(a.Transport, a.Address), a.ExpireOn)
226 247
 }
227 248
 
249
+// HelloMsg
228 250
 type HelloMsg struct {
229 251
 	MsgSize    uint16          `order:"big"` // total size of message
230 252
 	MsgType    uint16          `order:"big"` // HELLO (17)
@@ -233,6 +255,7 @@ type HelloMsg struct {
233 255
 	Addresses  []*HelloAddress `size:"*"` // List of end-point addressess
234 256
 }
235 257
 
258
+// NewHelloMsg creates a new HELLO msg for a given peer.
236 259
 func NewHelloMsg(peerid *util.PeerID) *HelloMsg {
237 260
 	if peerid == nil {
238 261
 		peerid = util.NewPeerID(nil)
@@ -246,11 +269,13 @@ func NewHelloMsg(peerid *util.PeerID) *HelloMsg {
246 269
 	}
247 270
 }
248 271
 
272
+// String returns a human-readable representation of the message.
249 273
 func (m *HelloMsg) String() string {
250 274
 	return fmt.Sprintf("HelloMsg{peer=%s,friendsonly=%d,addr=%v}",
251 275
 		m.PeerID, m.FriendOnly, m.Addresses)
252 276
 }
253 277
 
278
+// AddAddress adds a new address to the HELLO message.
254 279
 func (m *HelloMsg) AddAddress(a *HelloAddress) {
255 280
 	m.Addresses = append(m.Addresses, a)
256 281
 	m.MsgSize += uint16(len(a.Transport)) + a.AddrSize + 11
@@ -265,11 +290,13 @@ func (msg *HelloMsg) Header() *MessageHeader {
265 290
 // TRANSPORT_SESSION_ACK
266 291
 //----------------------------------------------------------------------
267 292
 
293
+// SessionAckMsg
268 294
 type SessionAckMsg struct {
269 295
 	MsgSize uint16 `order:"big"` // total size of message
270 296
 	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_ACK (377)
271 297
 }
272 298
 
299
+// NewSessionAckMsg creates an new message (no body required).
273 300
 func NewSessionAckMsg() *SessionAckMsg {
274 301
 	return &SessionAckMsg{
275 302
 		MsgSize: 16,
@@ -277,6 +304,7 @@ func NewSessionAckMsg() *SessionAckMsg {
277 304
 	}
278 305
 }
279 306
 
307
+// String returns a human-readable representation of the message.
280 308
 func (m *SessionAckMsg) String() string {
281 309
 	return "SessionAck{}"
282 310
 }
@@ -290,6 +318,7 @@ func (msg *SessionAckMsg) Header() *MessageHeader {
290 318
 // TRANSPORT_SESSION_SYN
291 319
 //----------------------------------------------------------------------
292 320
 
321
+// SessionSynMsg
293 322
 type SessionSynMsg struct {
294 323
 	MsgSize   uint16            `order:"big"` // total size of message
295 324
 	MsgType   uint16            `order:"big"` // TRANSPORT_SESSION_SYN (375)
@@ -297,6 +326,7 @@ type SessionSynMsg struct {
297 326
 	Timestamp util.AbsoluteTime // usec epoch
298 327
 }
299 328
 
329
+// NewSessionSynMsg creates a SYN request for the a session
300 330
 func NewSessionSynMsg() *SessionSynMsg {
301 331
 	return &SessionSynMsg{
302 332
 		MsgSize:   16,
@@ -306,6 +336,7 @@ func NewSessionSynMsg() *SessionSynMsg {
306 336
 	}
307 337
 }
308 338
 
339
+// String returns a human-readable representation of the message.
309 340
 func (m *SessionSynMsg) String() string {
310 341
 	return fmt.Sprintf("SessionSyn{timestamp=%s}", m.Timestamp)
311 342
 }
@@ -319,6 +350,7 @@ func (msg *SessionSynMsg) Header() *MessageHeader {
319 350
 // TRANSPORT_SESSION_SYN_ACK
320 351
 //----------------------------------------------------------------------
321 352
 
353
+// SessionSynAckMsg
322 354
 type SessionSynAckMsg struct {
323 355
 	MsgSize   uint16            `order:"big"` // total size of message
324 356
 	MsgType   uint16            `order:"big"` // TRANSPORT_SESSION_SYN_ACK (376)
@@ -326,6 +358,7 @@ type SessionSynAckMsg struct {
326 358
 	Timestamp util.AbsoluteTime // usec epoch
327 359
 }
328 360
 
361
+// NewSessionSynAckMsg is an ACK for a SYN request
329 362
 func NewSessionSynAckMsg() *SessionSynAckMsg {
330 363
 	return &SessionSynAckMsg{
331 364
 		MsgSize:   16,
@@ -335,6 +368,7 @@ func NewSessionSynAckMsg() *SessionSynAckMsg {
335 368
 	}
336 369
 }
337 370
 
371
+// String returns a human-readable representation of the message.
338 372
 func (m *SessionSynAckMsg) String() string {
339 373
 	return fmt.Sprintf("SessionSynAck{timestamp=%s}", m.Timestamp)
340 374
 }
@@ -348,12 +382,14 @@ func (msg *SessionSynAckMsg) Header() *MessageHeader {
348 382
 // TRANSPORT_SESSION_QUOTA
349 383
 //----------------------------------------------------------------------
350 384
 
385
+// SessionQuotaMsg
351 386
 type SessionQuotaMsg struct {
352 387
 	MsgSize uint16 `order:"big"` // total size of message
353 388
 	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_QUOTA (379)
354 389
 	Quota   uint32 `order:"big"` // Quota in bytes per second
355 390
 }
356 391
 
392
+// NewSessionQuotaMsg announces a session quota to the other end of the session.
357 393
 func NewSessionQuotaMsg(quota uint32) *SessionQuotaMsg {
358 394
 	m := new(SessionQuotaMsg)
359 395
 	if quota > 0 {
@@ -364,6 +400,7 @@ func NewSessionQuotaMsg(quota uint32) *SessionQuotaMsg {
364 400
 	return m
365 401
 }
366 402
 
403
+// String returns a human-readable representation of the message.
367 404
 func (m *SessionQuotaMsg) String() string {
368 405
 	return fmt.Sprintf("SessionQuotaMsg{%sB/s}", util.Scale1024(uint64(m.Quota)))
369 406
 }
@@ -374,57 +411,63 @@ func (msg *SessionQuotaMsg) Header() *MessageHeader {
374 411
 }
375 412
 
376 413
 //----------------------------------------------------------------------
377
-// TRANSPORT_SESSION_KEEPALIVE_RESPONSE
414
+// TRANSPORT_SESSION_KEEPALIVE
378 415
 //----------------------------------------------------------------------
379 416
 
380
-type SessionKeepAliveRespMsg struct {
417
+// SessionKeepAliveMsg
418
+type SessionKeepAliveMsg struct {
381 419
 	MsgSize uint16 `order:"big"` // total size of message
382
-	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_KEEPALIVE_RESPONSE (382)
420
+	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_KEEPALIVE (381)
383 421
 	Nonce   uint32
384 422
 }
385 423
 
386
-func NewSessionKeepAliveRespMsg(nonce uint32) *SessionKeepAliveRespMsg {
387
-	m := &SessionKeepAliveRespMsg{
424
+// NewSessionKeepAliveMsg creates a new request to keep a session.
425
+func NewSessionKeepAliveMsg() *SessionKeepAliveMsg {
426
+	m := &SessionKeepAliveMsg{
388 427
 		MsgSize: 8,
389
-		MsgType: TRANSPORT_SESSION_KEEPALIVE_RESPONSE,
390
-		Nonce:   nonce,
428
+		MsgType: TRANSPORT_SESSION_KEEPALIVE,
429
+		Nonce:   util.RndUInt32(),
391 430
 	}
392 431
 	return m
393 432
 }
394 433
 
395
-func (m *SessionKeepAliveRespMsg) String() string {
396
-	return fmt.Sprintf("SessionKeepAliveRespMsg{%d}", m.Nonce)
434
+// String returns a human-readable representation of the message.
435
+func (m *SessionKeepAliveMsg) String() string {
436
+	return fmt.Sprintf("SessionKeepAliveMsg{%d}", m.Nonce)
397 437
 }
398 438
 
399 439
 // Header returns the message header in a separate instance.
400
-func (msg *SessionKeepAliveRespMsg) Header() *MessageHeader {
440
+func (msg *SessionKeepAliveMsg) Header() *MessageHeader {
401 441
 	return &MessageHeader{msg.MsgSize, msg.MsgType}
402 442
 }
403 443
 
404 444
 //----------------------------------------------------------------------
405
-// TRANSPORT_SESSION_KEEPALIVE
445
+// TRANSPORT_SESSION_KEEPALIVE_RESPONSE
406 446
 //----------------------------------------------------------------------
407 447
 
408
-type SessionKeepAliveMsg struct {
448
+// SessionKeepAliveRespMsg
449
+type SessionKeepAliveRespMsg struct {
409 450
 	MsgSize uint16 `order:"big"` // total size of message
410
-	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_KEEPALIVE (381)
451
+	MsgType uint16 `order:"big"` // TRANSPORT_SESSION_KEEPALIVE_RESPONSE (382)
411 452
 	Nonce   uint32
412 453
 }
413 454
 
414
-func NewSessionKeepAliveMsg() *SessionKeepAliveMsg {
415
-	m := &SessionKeepAliveMsg{
455
+// NewSessionKeepAliveRespMsg is a response message for a "keep session" request.
456
+func NewSessionKeepAliveRespMsg(nonce uint32) *SessionKeepAliveRespMsg {
457
+	m := &SessionKeepAliveRespMsg{
416 458
 		MsgSize: 8,
417
-		MsgType: TRANSPORT_SESSION_KEEPALIVE,
418
-		Nonce:   util.RndUInt32(),
459
+		MsgType: TRANSPORT_SESSION_KEEPALIVE_RESPONSE,
460
+		Nonce:   nonce,
419 461
 	}
420 462
 	return m
421 463
 }
422 464
 
423
-func (m *SessionKeepAliveMsg) String() string {
424
-	return fmt.Sprintf("SessionKeepAliveMsg{%d}", m.Nonce)
465
+// String returns a human-readable representation of the message.
466
+func (m *SessionKeepAliveRespMsg) String() string {
467
+	return fmt.Sprintf("SessionKeepAliveRespMsg{%d}", m.Nonce)
425 468
 }
426 469
 
427 470
 // Header returns the message header in a separate instance.
428
-func (msg *SessionKeepAliveMsg) Header() *MessageHeader {
471
+func (msg *SessionKeepAliveRespMsg) Header() *MessageHeader {
429 472
 	return &MessageHeader{msg.MsgSize, msg.MsgType}
430 473
 }

+ 2
- 1
src/gnunet/service/client.go View File

@@ -1,9 +1,10 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/bfix/gospel/logger"
5 4
 	"gnunet/message"
6 5
 	"gnunet/transport"
6
+
7
+	"github.com/bfix/gospel/logger"
7 8
 )
8 9
 
9 10
 // Client

+ 2
- 1
src/gnunet/service/service.go View File

@@ -3,8 +3,9 @@ package service
3 3
 import (
4 4
 	"fmt"
5 5
 
6
-	"github.com/bfix/gospel/logger"
7 6
 	"gnunet/transport"
7
+
8
+	"github.com/bfix/gospel/logger"
8 9
 )
9 10
 
10 11
 // Service is an interface for GNUnet services. Every service has one channel

+ 1
- 0
src/gnunet/transport/channel.go View File

@@ -11,6 +11,7 @@ import (
11 11
 	"gnunet/message"
12 12
 )
13 13
 
14
+// Error codes
14 15
 var (
15 16
 	ErrChannelNotImplemented = fmt.Errorf("Protocol not implemented")
16 17
 	ErrChannelNotOpened      = fmt.Errorf("Channel not opened")

+ 28
- 11
src/gnunet/transport/channel_netw.go View File

@@ -14,11 +14,12 @@ import (
14 14
 
15 15
 // NetworkChannel
16 16
 type NetworkChannel struct {
17
-	network string
18
-	conn    net.Conn
17
+	network string   // network protocol identifier ("tcp", "unix", ...)
18
+	conn    net.Conn // associated connection
19 19
 }
20 20
 
21
-// NewNetworkChannel
21
+// NewNetworkChannel creates a new channel for a given network protocol.
22
+// The channel is in pending state and need to be opened before use.
22 23
 func NewNetworkChannel(netw string) Channel {
23 24
 	return &NetworkChannel{
24 25
 		network: netw,
@@ -26,7 +27,11 @@ func NewNetworkChannel(netw string) Channel {
26 27
 	}
27 28
 }
28 29
 
29
-// Open
30
+// Open a network channel based on specification:
31
+// The specification is a string separated into parts by the '+' delimiter
32
+// (e.g. "unix+/tmp/gnunet-service-gns-go.sock+perm=0770"). The network
33
+// identifier (first part) must match the network specification of the
34
+// underlaying NetworkChannel instance.
30 35
 func (c *NetworkChannel) Open(spec string) (err error) {
31 36
 	parts := strings.Split(spec, "+")
32 37
 	// check for correct protocol
@@ -38,7 +43,7 @@ func (c *NetworkChannel) Open(spec string) (err error) {
38 43
 	return
39 44
 }
40 45
 
41
-// Close
46
+// Close a network channel
42 47
 func (c *NetworkChannel) Close() error {
43 48
 	if c.conn != nil {
44 49
 		return c.conn.Close()
@@ -46,7 +51,8 @@ func (c *NetworkChannel) Close() error {
46 51
 	return ErrChannelNotOpened
47 52
 }
48 53
 
49
-// Read
54
+// Read bytes from a network channel into buffer: Returns the number of read
55
+// bytes and an error code. Only works on open channels ;)
50 56
 func (c *NetworkChannel) Read(buf []byte) (int, error) {
51 57
 	if c.conn == nil {
52 58
 		return 0, ErrChannelNotOpened
@@ -54,7 +60,8 @@ func (c *NetworkChannel) Read(buf []byte) (int, error) {
54 60
 	return c.conn.Read(buf)
55 61
 }
56 62
 
57
-// Write
63
+// Write buffer to a network channel: Returns the number of written bytes and
64
+// an error code.
58 65
 func (c *NetworkChannel) Write(buf []byte) (int, error) {
59 66
 	if c.conn == nil {
60 67
 		return 0, ErrChannelNotOpened
@@ -67,8 +74,8 @@ func (c *NetworkChannel) Write(buf []byte) (int, error) {
67 74
 
68 75
 // NetworkChannelServer
69 76
 type NetworkChannelServer struct {
70
-	network  string
71
-	listener net.Listener
77
+	network  string       // network protocol to listen on
78
+	listener net.Listener // reference to listener object
72 79
 }
73 80
 
74 81
 // NewNetworkChannelServer
@@ -79,7 +86,9 @@ func NewNetworkChannelServer(netw string) ChannelServer {
79 86
 	}
80 87
 }
81 88
 
82
-// Open
89
+// Open a network channel server (= start running it) based on the given
90
+// specification. For every client connection to the server, the associated
91
+// network channel for the connection is send via the hdlr channel.
83 92
 func (s *NetworkChannelServer) Open(spec string, hdlr chan<- Channel) (err error) {
84 93
 	parts := strings.Split(spec, "+")
85 94
 	// check for correct protocol
@@ -136,7 +145,7 @@ func (s *NetworkChannelServer) Open(spec string, hdlr chan<- Channel) (err error
136 145
 	return nil
137 146
 }
138 147
 
139
-// Close
148
+// Close a network channel server (= stop the server)
140 149
 func (s *NetworkChannelServer) Close() error {
141 150
 	if s.listener != nil {
142 151
 		err := s.listener.Close()
@@ -147,27 +156,35 @@ func (s *NetworkChannelServer) Close() error {
147 156
 }
148 157
 
149 158
 ////////////////////////////////////////////////////////////////////////
159
+// helper functions to instantiate network channels and servers for
160
+// common network protocols
150 161
 
162
+// NewSocketChannel: Unix Domain Socket connection
151 163
 func NewSocketChannel() Channel {
152 164
 	return NewNetworkChannel("unix")
153 165
 }
154 166
 
167
+// NewTCPChannel: TCP connection
155 168
 func NewTCPChannel() Channel {
156 169
 	return NewNetworkChannel("tcp")
157 170
 }
158 171
 
172
+// NewUDPChannel: UDP connection
159 173
 func NewUDPChannel() Channel {
160 174
 	return NewNetworkChannel("udp")
161 175
 }
162 176
 
177
+// NewSocketChannelServer: Unix Domain Socket listener
163 178
 func NewSocketChannelServer() ChannelServer {
164 179
 	return NewNetworkChannelServer("unix")
165 180
 }
166 181
 
182
+// NewTCPChannelServer: TCP listener
167 183
 func NewTCPChannelServer() ChannelServer {
168 184
 	return NewNetworkChannelServer("tcp")
169 185
 }
170 186
 
187
+// NewUDPChannelServer: UDP listener
171 188
 func NewUDPChannelServer() ChannelServer {
172 189
 	return NewNetworkChannelServer("udp")
173 190
 }

+ 8
- 1
src/gnunet/transport/connection.go View File

@@ -5,7 +5,6 @@ import (
5 5
 	"gnunet/message"
6 6
 )
7 7
 
8
-////////////////////////////////////////////////////////////////////////
9 8
 // Connection for communicating peers
10 9
 type Connection struct {
11 10
 	from, to  *core.Peer
@@ -17,6 +16,8 @@ type Connection struct {
17 16
 	shared    []byte
18 17
 }
19 18
 
19
+// NewConnection instanciates a new connection between peers communicating
20
+// over a message channel (Connections are authenticated and secured).
20 21
 func NewConnection(ch *MsgChannel, from, to *core.Peer) *Connection {
21 22
 	return &Connection{
22 23
 		from:  from,
@@ -26,27 +27,33 @@ func NewConnection(ch *MsgChannel, from, to *core.Peer) *Connection {
26 27
 	}
27 28
 }
28 29
 
30
+// SharedSecret computes the shared secret the two endpoints of a connection.
29 31
 func (c *Connection) SharedSecret(secret []byte) {
30 32
 	c.shared = make([]byte, len(secret))
31 33
 	copy(c.shared, secret)
32 34
 }
33 35
 
36
+// GetState returns the current state of the connection.
34 37
 func (c *Connection) GetState() int {
35 38
 	return c.state
36 39
 }
37 40
 
41
+// SetBandwidth to control transfer rates on the connection
38 42
 func (c *Connection) SetBandwidth(bw uint32) {
39 43
 	c.bandwidth = bw
40 44
 }
41 45
 
46
+// Close connection between two peers.
42 47
 func (c *Connection) Close() error {
43 48
 	return c.ch.Close()
44 49
 }
45 50
 
51
+// Send a message on the connection
46 52
 func (c *Connection) Send(msg message.Message) error {
47 53
 	return c.ch.Send(msg)
48 54
 }
49 55
 
56
+// Receive a message on the connection
50 57
 func (c *Connection) Receive() (message.Message, error) {
51 58
 	return c.ch.Receive()
52 59
 }

+ 1
- 2
src/gnunet/transport/session.go View File

@@ -1,7 +1,6 @@
1 1
 package transport
2 2
 
3
-import ()
4
-
3
+// Session states
5 4
 const (
6 5
 	KX_STATE_DOWN         = iota // No handshake yet.
7 6
 	KX_STATE_KEY_SENT            // We've sent our session key.

+ 38
- 17
src/gnunet/util/address.go View File

@@ -1,29 +1,19 @@
1 1
 package util
2 2
 
3 3
 import (
4
+	"encoding/hex"
4 5
 	"fmt"
6
+	"net"
5 7
 )
6 8
 
7
-type IPAddress struct {
8
-	Host []byte `size:"*-2"`
9
-	Port uint16 `order:"big"`
10
-}
11
-
12
-func NewIPAddress(host []byte, port uint16) *IPAddress {
13
-	ip := &IPAddress{
14
-		Host: make([]byte, len(host)),
15
-		Port: port,
16
-	}
17
-	copy(ip.Host, host)
18
-	return ip
19
-}
20
-
9
+// Address specifies how a peer is reachable on the network.
21 10
 type Address struct {
22
-	Transport string
23
-	Options   uint32 `order:"big"`
24
-	Address   []byte `size:"*"`
11
+	Transport string // transport protocol
12
+	Options   uint32 `order:"big"` // address options
13
+	Address   []byte `size:"*"`    // address data (protocol-dependent)
25 14
 }
26 15
 
16
+// NewAddress returns a new Address for the given transport and specs
27 17
 func NewAddress(transport string, addr []byte) *Address {
28 18
 	a := &Address{
29 19
 		Transport: transport,
@@ -34,6 +24,37 @@ func NewAddress(transport string, addr []byte) *Address {
34 24
 	return a
35 25
 }
36 26
 
27
+// String returns a human-readable representation of an address.
37 28
 func (a *Address) String() string {
38 29
 	return fmt.Sprintf("Address{%s}", AddressString(a.Transport, a.Address))
39 30
 }
31
+
32
+//----------------------------------------------------------------------
33
+
34
+// AddressString returns a string representaion of an address.
35
+func AddressString(transport string, addr []byte) string {
36
+	if transport == "tcp" || transport == "udp" {
37
+		alen := len(addr)
38
+		port := uint(addr[alen-2])*256 + uint(addr[alen-1])
39
+		return fmt.Sprintf("%s:%s:%d", transport, net.IP(addr[:alen-2]).String(), port)
40
+	}
41
+	return fmt.Sprintf("%s:%s", transport, hex.EncodeToString(addr))
42
+}
43
+
44
+//----------------------------------------------------------------------
45
+
46
+// IP address (can be IPv4 or IPv6 or a DNS name)
47
+type IPAddress struct {
48
+	Host []byte `size:"*-2"`
49
+	Port uint16 `order:"big"`
50
+}
51
+
52
+// NewIPAddress creates a new instance for a given host and port.
53
+func NewIPAddress(host []byte, port uint16) *IPAddress {
54
+	ip := &IPAddress{
55
+		Host: make([]byte, len(host)),
56
+		Port: port,
57
+	}
58
+	copy(ip.Host, host)
59
+	return ip
60
+}

+ 2
- 11
src/gnunet/util/format.go View File

@@ -1,22 +1,13 @@
1 1
 package util
2 2
 
3 3
 import (
4
-	"encoding/hex"
5 4
 	"fmt"
6
-	"net"
7 5
 )
8 6
 
9
-func AddressString(transport string, addr []byte) string {
10
-	if transport == "tcp" || transport == "udp" {
11
-		alen := len(addr)
12
-		port := uint(addr[alen-2])*256 + uint(addr[alen-1])
13
-		return fmt.Sprintf("%s:%s:%d", transport, net.IP(addr[:alen-2]).String(), port)
14
-	}
15
-	return fmt.Sprintf("%s:%s", transport, hex.EncodeToString(addr))
16
-}
17
-
18 7
 var scale = " kMGTPEO"
19 8
 
9
+// Scale1024 returns an integer value (e.g. a size) as a human-readable
10
+// string with scales: a size of 183467245 would result in "174,967M"
20 11
 func Scale1024(n uint64) string {
21 12
 	v := float64(n)
22 13
 	var i int

+ 2
- 1
src/gnunet/util/id.go View File

@@ -4,7 +4,8 @@ var (
4 4
 	_id = 0
5 5
 )
6 6
 
7
+// generate next unique identifier (unique in the running process/application)
7 8
 func NextID() int {
8
-	_id += 1
9
+	_id++
9 10
 	return _id
10 11
 }

+ 0
- 3
src/gnunet/util/msg_queue.go View File

@@ -1,3 +0,0 @@
1
-package util
2
-
3
-import ()

+ 3
- 0
src/gnunet/util/peer_id.go View File

@@ -1,9 +1,11 @@
1 1
 package util
2 2
 
3
+// PeerID is the 32-byte binary representation od a Ed25519 key
3 4
 type PeerID struct {
4 5
 	Key []byte `size:"32"`
5 6
 }
6 7
 
8
+// NewPeerID creates a new object from the data.
7 9
 func NewPeerID(data []byte) *PeerID {
8 10
 	if data == nil {
9 11
 		data = make([]byte, 32)
@@ -22,6 +24,7 @@ func NewPeerID(data []byte) *PeerID {
22 24
 	}
23 25
 }
24 26
 
27
+// String returns a human-readable representation of a peer id.
25 28
 func (p *PeerID) String() string {
26 29
 	return EncodeBinaryToString(p.Key)
27 30
 }

+ 8
- 0
src/gnunet/util/rnd.go View File

@@ -6,16 +6,19 @@ import (
6 6
 	"encoding/binary"
7 7
 )
8 8
 
9
+// RndArray fills a buffer with random content
9 10
 func RndArray(b []byte) {
10 11
 	rand.Read(b)
11 12
 }
12 13
 
14
+// NewRndArray creates a new buffer of given size; filled with random content.
13 15
 func NewRndArray(size int) []byte {
14 16
 	b := make([]byte, size)
15 17
 	rand.Read(b)
16 18
 	return b
17 19
 }
18 20
 
21
+// RndUInt64 returns a new 64-bit unsigned random integer.
19 22
 func RndUInt64() uint64 {
20 23
 	b := make([]byte, 8)
21 24
 	RndArray(b)
@@ -25,22 +28,27 @@ func RndUInt64() uint64 {
25 28
 	return v
26 29
 }
27 30
 
31
+// RndInt64 returns a new 64-bit signed random integer.
28 32
 func RndInt64() int64 {
29 33
 	return int64(RndUInt64())
30 34
 }
31 35
 
36
+// RndUInt32 returns a new 32-bit unsigned random integer.
32 37
 func RndUInt32() uint32 {
33 38
 	return uint32(RndUInt64())
34 39
 }
35 40
 
41
+// RndInt32 returns a new 32-bit signed random integer.
36 42
 func RndInt32() int32 {
37 43
 	return int32(RndUInt64())
38 44
 }
39 45
 
46
+// RndUInt16 returns a new 16-bit unsigned random integer.
40 47
 func RndUInt16() uint16 {
41 48
 	return uint16(RndUInt64())
42 49
 }
43 50
 
51
+// RndInt16 returns a new 16-bit signed random integer.
44 52
 func RndInt16() int16 {
45 53
 	return int16(RndUInt64())
46 54
 }

Loading…
Cancel
Save