2017-12-29 04:16:20 +00:00
package yggdrasil
2018-11-10 05:02:38 +00:00
// A chord-like Distributed Hash Table (DHT).
// Used to look up coords given a NodeID and bitmask (taken from an IPv6 address).
// Keeps track of immediate successor, predecessor, and all peers.
// Also keeps track of other nodes if they're closer in tree space than all other known nodes encountered when heading in either direction to that point, under the hypothesis that, for the kinds of networks we care about, this should probabilistically include the node needed to keep lookups to near O(logn) steps.
2018-10-25 03:03:27 +00:00
2018-06-12 22:50:08 +00:00
import (
"sort"
"time"
2018-12-15 02:49:18 +00:00
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
2018-06-12 22:50:08 +00:00
)
2017-12-29 04:16:20 +00:00
2018-12-21 02:16:51 +00:00
const (
dht_lookup_size = 16
dht_timeout = 6 * time . Minute
dht_max_delay = 5 * time . Minute
dht_max_delay_dirty = 30 * time . Second
)
2018-06-10 23:03:28 +00:00
// dhtInfo represents everything we know about a node in the DHT.
// This includes its key, a cache of it's NodeID, coords, and timing/ping related info for deciding who/when to ping nodes for maintenance.
2017-12-29 04:16:20 +00:00
type dhtInfo struct {
2018-12-15 02:49:18 +00:00
nodeID_hidden * crypto . NodeID
key crypto . BoxPubKey
2018-01-04 22:37:51 +00:00
coords [ ] byte
2018-10-20 19:48:07 +00:00
recv time . Time // When we last received a message
2018-10-21 01:11:32 +00:00
pings int // Time out if at least 3 consecutive maintenance pings drop
2018-10-21 03:06:36 +00:00
throttle time . Duration
2018-12-21 02:16:51 +00:00
dirty bool // Set to true if we've used this node in ping responses (for queries about someone other than the person doing the asking, i.e. real searches) since the last time we heard from the node
2017-12-29 04:16:20 +00:00
}
2018-06-10 23:03:28 +00:00
// Returns the *NodeID associated with dhtInfo.key, calculating it on the fly the first time or from a cache all subsequent times.
2018-12-15 02:49:18 +00:00
func ( info * dhtInfo ) getNodeID ( ) * crypto . NodeID {
2018-01-04 22:37:51 +00:00
if info . nodeID_hidden == nil {
2018-12-15 02:49:18 +00:00
info . nodeID_hidden = crypto . GetNodeID ( & info . key )
2018-01-04 22:37:51 +00:00
}
return info . nodeID_hidden
2017-12-29 04:16:20 +00:00
}
2018-06-10 23:03:28 +00:00
// Request for a node to do a lookup.
// Includes our key and coords so they can send a response back, and the destination NodeID we want to ask about.
2017-12-29 04:16:20 +00:00
type dhtReq struct {
2018-12-15 02:49:18 +00:00
Key crypto . BoxPubKey // Key of whoever asked
Coords [ ] byte // Coords of whoever asked
Dest crypto . NodeID // NodeID they're asking about
2017-12-29 04:16:20 +00:00
}
2018-06-10 23:03:28 +00:00
// Response to a DHT lookup.
// Includes the key and coords of the node that's responding, and the destination they were asked about.
// The main part is Infos []*dhtInfo, the lookup response.
2017-12-29 04:16:20 +00:00
type dhtRes struct {
2018-12-15 02:49:18 +00:00
Key crypto . BoxPubKey // key of the sender
Coords [ ] byte // coords of the sender
Dest crypto . NodeID
2018-06-02 21:19:42 +00:00
Infos [ ] * dhtInfo // response
2017-12-29 04:16:20 +00:00
}
2018-11-25 22:10:32 +00:00
// Parts of a DHT req usable as a key in a map.
type dhtReqKey struct {
2018-12-15 02:49:18 +00:00
key crypto . BoxPubKey
dest crypto . NodeID
2018-11-25 22:10:32 +00:00
}
2018-06-10 23:03:28 +00:00
// The main DHT struct.
2017-12-29 04:16:20 +00:00
type dht struct {
2019-08-25 17:10:59 +00:00
router * router
nodeID crypto . NodeID
reqs map [ dhtReqKey ] time . Time // Keeps track of recent outstanding requests
callbacks map [ dhtReqKey ] [ ] dht_callbackInfo // Search and admin lookup callbacks
2018-10-30 03:24:18 +00:00
// These next two could be replaced by a single linked list or similar...
2018-12-15 02:49:18 +00:00
table map [ crypto . NodeID ] * dhtInfo
2018-10-30 03:24:18 +00:00
imp [ ] * dhtInfo
2017-12-29 04:16:20 +00:00
}
2018-11-10 05:02:38 +00:00
// Initializes the DHT.
2019-08-24 01:35:54 +00:00
func ( t * dht ) init ( r * router ) {
t . router = r
t . nodeID = * t . router . core . NodeID ( )
2019-06-26 00:31:29 +00:00
t . callbacks = make ( map [ dhtReqKey ] [ ] dht_callbackInfo )
2018-10-20 19:48:07 +00:00
t . reset ( )
}
2019-08-25 17:10:59 +00:00
func ( t * dht ) reconfigure ( e chan error ) {
defer close ( e )
// This is where reconfiguration would go, if we had anything to do
}
2018-11-10 05:02:38 +00:00
// Resets the DHT in response to coord changes.
// This empties all info from the DHT and drops outstanding requests.
2018-10-20 19:48:07 +00:00
func ( t * dht ) reset ( ) {
2018-11-25 22:10:32 +00:00
t . reqs = make ( map [ dhtReqKey ] time . Time )
2018-12-15 02:49:18 +00:00
t . table = make ( map [ crypto . NodeID ] * dhtInfo )
2018-10-30 03:24:18 +00:00
t . imp = nil
2018-10-20 19:48:07 +00:00
}
2018-11-10 05:02:38 +00:00
// Does a DHT lookup and returns up to dht_lookup_size results.
2018-12-15 02:49:18 +00:00
func ( t * dht ) lookup ( nodeID * crypto . NodeID , everything bool ) [ ] * dhtInfo {
2018-10-21 22:40:43 +00:00
results := make ( [ ] * dhtInfo , 0 , len ( t . table ) )
for _ , info := range t . table {
results = append ( results , info )
}
if len ( results ) > dht_lookup_size {
2018-11-17 01:32:12 +00:00
// Drop the middle part, so we keep some nodes before and after.
// This should help to bootstrap / recover more quickly.
sort . SliceStable ( results , func ( i , j int ) bool {
return dht_ordered ( nodeID , results [ i ] . getNodeID ( ) , results [ j ] . getNodeID ( ) )
} )
newRes := make ( [ ] * dhtInfo , 0 , len ( results ) )
newRes = append ( newRes , results [ len ( results ) - dht_lookup_size / 2 : ] ... )
newRes = append ( newRes , results [ : len ( results ) - dht_lookup_size / 2 ] ... )
results = newRes
2018-10-21 23:15:04 +00:00
results = results [ : dht_lookup_size ]
2018-10-20 19:48:07 +00:00
}
return results
}
2018-11-10 05:02:38 +00:00
// Insert into table, preserving the time we last sent a packet if the node was already in the table, otherwise setting that time to now.
2018-10-20 19:48:07 +00:00
func ( t * dht ) insert ( info * dhtInfo ) {
2018-10-20 20:21:40 +00:00
if * info . getNodeID ( ) == t . nodeID {
2018-10-20 22:32:54 +00:00
// This shouldn't happen, but don't add it if it does
2018-10-20 20:21:40 +00:00
return
}
2018-10-20 19:48:07 +00:00
info . recv = time . Now ( )
2018-10-21 03:06:36 +00:00
if oldInfo , isIn := t . table [ * info . getNodeID ( ) ] ; isIn {
sameCoords := true
if len ( info . coords ) != len ( oldInfo . coords ) {
sameCoords = false
} else {
for idx := 0 ; idx < len ( info . coords ) ; idx ++ {
if info . coords [ idx ] != oldInfo . coords [ idx ] {
sameCoords = false
break
}
}
}
if sameCoords {
info . throttle = oldInfo . throttle
}
}
2018-10-30 03:24:18 +00:00
t . imp = nil // It needs to update to get a pointer to the new info
2018-10-20 19:48:07 +00:00
t . table [ * info . getNodeID ( ) ] = info
}
2018-12-20 23:37:59 +00:00
// Insert a peer into the table if it hasn't been pinged lately, to keep peers from dropping
func ( t * dht ) insertPeer ( info * dhtInfo ) {
oldInfo , isIn := t . table [ * info . getNodeID ( ) ]
2018-12-21 02:16:51 +00:00
if ! isIn || time . Since ( oldInfo . recv ) > dht_max_delay + 30 * time . Second {
2018-12-20 23:37:59 +00:00
// TODO? also check coords?
2018-12-26 06:18:51 +00:00
newInfo := * info // Insert a copy
t . insert ( & newInfo )
2018-12-20 23:37:59 +00:00
}
}
2018-11-10 05:02:38 +00:00
// Return true if first/second/third are (partially) ordered correctly.
2018-12-15 02:49:18 +00:00
func dht_ordered ( first , second , third * crypto . NodeID ) bool {
lessOrEqual := func ( first , second * crypto . NodeID ) bool {
for idx := 0 ; idx < crypto . NodeIDLen ; idx ++ {
2018-10-21 05:05:04 +00:00
if first [ idx ] > second [ idx ] {
return false
}
if first [ idx ] < second [ idx ] {
return true
}
2018-10-20 19:48:07 +00:00
}
2018-10-21 05:05:04 +00:00
return true
}
firstLessThanSecond := lessOrEqual ( first , second )
secondLessThanThird := lessOrEqual ( second , third )
thirdLessThanFirst := lessOrEqual ( third , first )
switch {
case firstLessThanSecond && secondLessThanThird :
// Nothing wrapped around 0, the easy case
return true
case thirdLessThanFirst && firstLessThanSecond :
// Third wrapped around 0
return true
case secondLessThanThird && thirdLessThanFirst :
// Second (and third) wrapped around 0
return true
2018-10-20 19:48:07 +00:00
}
2018-10-21 05:05:04 +00:00
return false
2017-12-29 04:16:20 +00:00
}
2018-06-10 23:03:28 +00:00
// Reads a request, performs a lookup, and responds.
2018-10-20 19:48:07 +00:00
// Update info about the node that sent the request.
2017-12-29 04:16:20 +00:00
func ( t * dht ) handleReq ( req * dhtReq ) {
2018-01-04 22:37:51 +00:00
// Send them what they asked for
2019-08-24 01:35:54 +00:00
loc := t . router . core . switchTable . getLocator ( )
2018-01-04 22:37:51 +00:00
coords := loc . getCoords ( )
res := dhtRes {
2019-08-24 01:35:54 +00:00
Key : t . router . core . boxPub ,
2018-06-02 21:19:42 +00:00
Coords : coords ,
Dest : req . Dest ,
Infos : t . lookup ( & req . Dest , false ) ,
2018-01-04 22:37:51 +00:00
}
t . sendRes ( & res , req )
2018-10-20 20:21:40 +00:00
// Also add them to our DHT
2018-01-04 22:37:51 +00:00
info := dhtInfo {
2018-06-02 21:19:42 +00:00
key : req . Key ,
coords : req . Coords ,
2018-01-04 22:37:51 +00:00
}
2018-11-10 05:02:38 +00:00
if _ , isIn := t . table [ * info . getNodeID ( ) ] ; ! isIn && t . isImportant ( & info ) {
2018-11-17 01:32:12 +00:00
t . ping ( & info , nil )
2018-10-25 03:03:27 +00:00
}
2018-12-21 02:16:51 +00:00
// Maybe mark nodes from lookup as dirty
if req . Dest != * info . getNodeID ( ) {
// This node asked about someone other than themself, so this wasn't just idle traffic.
for _ , info := range res . Infos {
// Mark nodes dirty so we're sure to check up on them again later
info . dirty = true
}
}
2018-10-20 19:48:07 +00:00
}
// Sends a lookup response to the specified node.
func ( t * dht ) sendRes ( res * dhtRes , req * dhtReq ) {
// Send a reply for a dhtReq
bs := res . encode ( )
2019-08-24 01:35:54 +00:00
shared := t . router . sessions . getSharedKey ( & t . router . core . boxPriv , & req . Key )
2018-12-15 02:49:18 +00:00
payload , nonce := crypto . BoxSeal ( shared , bs , nil )
2018-10-20 19:48:07 +00:00
p := wire_protoTrafficPacket {
Coords : req . Coords ,
ToKey : req . Key ,
2019-08-24 01:35:54 +00:00
FromKey : t . router . core . boxPub ,
2018-10-20 19:48:07 +00:00
Nonce : * nonce ,
Payload : payload ,
}
packet := p . encode ( )
2019-08-24 01:35:54 +00:00
t . router . out ( packet )
2018-10-20 19:48:07 +00:00
}
2018-11-25 23:08:45 +00:00
type dht_callbackInfo struct {
f func ( * dhtRes )
time time . Time
}
2018-11-25 22:10:32 +00:00
// Adds a callback and removes it after some timeout.
func ( t * dht ) addCallback ( rq * dhtReqKey , callback func ( * dhtRes ) ) {
2018-11-25 23:08:45 +00:00
info := dht_callbackInfo { callback , time . Now ( ) . Add ( 6 * time . Second ) }
2019-06-26 00:31:29 +00:00
t . callbacks [ * rq ] = append ( t . callbacks [ * rq ] , info )
2018-11-25 22:10:32 +00:00
}
2018-06-10 23:03:28 +00:00
// Reads a lookup response, checks that we had sent a matching request, and processes the response info.
2018-10-20 19:48:07 +00:00
// This mainly consists of updating the node we asked in our DHT (they responded, so we know they're still alive), and deciding if we want to do anything with their responses
2017-12-29 04:16:20 +00:00
func ( t * dht ) handleRes ( res * dhtRes ) {
2018-11-25 22:10:32 +00:00
rq := dhtReqKey { res . Key , res . Dest }
2019-06-26 00:31:29 +00:00
if callbacks , isIn := t . callbacks [ rq ] ; isIn {
for _ , callback := range callbacks {
callback . f ( res )
}
2018-11-25 23:08:45 +00:00
delete ( t . callbacks , rq )
2018-01-04 22:37:51 +00:00
}
2018-11-25 22:10:32 +00:00
_ , isIn := t . reqs [ rq ]
2018-01-04 22:37:51 +00:00
if ! isIn {
return
}
2018-11-25 22:10:32 +00:00
delete ( t . reqs , rq )
2018-01-04 22:37:51 +00:00
rinfo := dhtInfo {
2018-10-20 19:48:07 +00:00
key : res . Key ,
coords : res . Coords ,
}
2018-11-10 05:02:38 +00:00
if t . isImportant ( & rinfo ) {
2018-10-25 03:03:27 +00:00
t . insert ( & rinfo )
}
2018-06-02 21:19:42 +00:00
for _ , info := range res . Infos {
2018-10-20 19:48:07 +00:00
if * info . getNodeID ( ) == t . nodeID {
2018-05-18 02:20:31 +00:00
continue
2018-10-20 19:48:07 +00:00
} // Skip self
2018-10-20 20:21:40 +00:00
if _ , isIn := t . table [ * info . getNodeID ( ) ] ; isIn {
// TODO? don't skip if coords are different?
continue
}
2018-11-10 05:02:38 +00:00
if t . isImportant ( info ) {
2018-10-21 17:28:21 +00:00
t . ping ( info , nil )
2018-01-04 22:37:51 +00:00
}
}
2017-12-29 04:16:20 +00:00
}
2018-06-10 23:03:28 +00:00
// Sends a lookup request to the specified node.
2017-12-29 04:16:20 +00:00
func ( t * dht ) sendReq ( req * dhtReq , dest * dhtInfo ) {
2018-01-04 22:37:51 +00:00
// Send a dhtReq to the node in dhtInfo
bs := req . encode ( )
2019-08-24 01:35:54 +00:00
shared := t . router . sessions . getSharedKey ( & t . router . core . boxPriv , & dest . key )
2018-12-15 02:49:18 +00:00
payload , nonce := crypto . BoxSeal ( shared , bs , nil )
2018-01-04 22:37:51 +00:00
p := wire_protoTrafficPacket {
2018-06-02 20:21:05 +00:00
Coords : dest . coords ,
ToKey : dest . key ,
2019-08-24 01:35:54 +00:00
FromKey : t . router . core . boxPub ,
2018-06-02 20:21:05 +00:00
Nonce : * nonce ,
Payload : payload ,
2018-01-04 22:37:51 +00:00
}
packet := p . encode ( )
2019-08-24 01:35:54 +00:00
t . router . out ( packet )
2018-11-25 23:08:45 +00:00
rq := dhtReqKey { dest . key , req . Dest }
2018-11-25 22:10:32 +00:00
t . reqs [ rq ] = time . Now ( )
2017-12-29 04:16:20 +00:00
}
2018-11-10 05:02:38 +00:00
// Sends a lookup to this info, looking for the target.
2018-12-15 02:49:18 +00:00
func ( t * dht ) ping ( info * dhtInfo , target * crypto . NodeID ) {
2018-10-20 19:48:07 +00:00
// Creates a req for the node at dhtInfo, asking them about the target (if one is given) or themself (if no target is given)
2018-01-04 22:37:51 +00:00
if target == nil {
2018-10-21 17:28:21 +00:00
target = & t . nodeID
2018-01-04 22:37:51 +00:00
}
2019-08-24 01:35:54 +00:00
loc := t . router . core . switchTable . getLocator ( )
2018-01-04 22:37:51 +00:00
coords := loc . getCoords ( )
req := dhtReq {
2019-08-24 01:35:54 +00:00
Key : t . router . core . boxPub ,
2018-06-02 21:19:42 +00:00
Coords : coords ,
Dest : * target ,
2018-01-04 22:37:51 +00:00
}
t . sendReq ( & req , info )
2017-12-29 04:16:20 +00:00
}
2018-11-10 05:02:38 +00:00
// Periodic maintenance work to keep important DHT nodes alive.
2017-12-29 04:16:20 +00:00
func ( t * dht ) doMaintenance ( ) {
2018-10-20 19:48:07 +00:00
now := time . Now ( )
2018-11-25 22:10:32 +00:00
newReqs := make ( map [ dhtReqKey ] time . Time , len ( t . reqs ) )
for key , start := range t . reqs {
if now . Sub ( start ) < 6 * time . Second {
newReqs [ key ] = start
2018-11-25 02:04:14 +00:00
}
}
2018-11-25 18:25:38 +00:00
t . reqs = newReqs
2019-06-26 00:31:29 +00:00
newCallbacks := make ( map [ dhtReqKey ] [ ] dht_callbackInfo , len ( t . callbacks ) )
for key , cs := range t . callbacks {
for _ , c := range cs {
if now . Before ( c . time ) {
newCallbacks [ key ] = append ( newCallbacks [ key ] , c )
} else {
// Signal failure
c . f ( nil )
}
2018-11-25 23:08:45 +00:00
}
2018-11-25 22:29:47 +00:00
}
t . callbacks = newCallbacks
2018-10-20 19:48:07 +00:00
for infoID , info := range t . table {
2018-12-21 23:45:24 +00:00
switch {
case info . pings > 6 :
// It failed to respond to too many pings
fallthrough
case now . Sub ( info . recv ) > dht_timeout :
// It's too old
fallthrough
case info . dirty && now . Sub ( info . recv ) > dht_max_delay_dirty && ! t . isImportant ( info ) :
// We won't ping it to refresh it, so just drop it
2018-10-20 19:48:07 +00:00
delete ( t . table , infoID )
2018-10-30 03:24:18 +00:00
t . imp = nil
2018-01-04 22:37:51 +00:00
}
}
2018-10-30 03:24:18 +00:00
for _ , info := range t . getImportant ( ) {
2018-12-21 02:16:51 +00:00
switch {
case now . Sub ( info . recv ) > info . throttle :
info . throttle *= 2
if info . throttle < time . Second {
info . throttle = time . Second
} else if info . throttle > dht_max_delay {
info . throttle = dht_max_delay
}
fallthrough
case info . dirty && now . Sub ( info . recv ) > dht_max_delay_dirty :
2018-11-17 01:32:12 +00:00
t . ping ( info , nil )
2018-10-21 17:28:21 +00:00
info . pings ++
}
}
2018-10-21 19:57:04 +00:00
}
2018-11-10 05:02:38 +00:00
// Gets a list of important nodes, used by isImportant.
2018-10-21 22:40:43 +00:00
func ( t * dht ) getImportant ( ) [ ] * dhtInfo {
2018-10-30 03:24:18 +00:00
if t . imp == nil {
// Get a list of all known nodes
infos := make ( [ ] * dhtInfo , 0 , len ( t . table ) )
for _ , info := range t . table {
infos = append ( infos , info )
2018-10-21 22:40:43 +00:00
}
2018-10-30 03:24:18 +00:00
// Sort them by increasing order in distance along the ring
sort . SliceStable ( infos , func ( i , j int ) bool {
// Sort in order of predecessors (!), reverse from chord normal, because it plays nicer with zero bits for unknown parts of target addresses
return dht_ordered ( infos [ j ] . getNodeID ( ) , infos [ i ] . getNodeID ( ) , & t . nodeID )
} )
// Keep the ones that are no further than the closest seen so far
minDist := ^ uint64 ( 0 )
2019-08-24 01:35:54 +00:00
loc := t . router . core . switchTable . getLocator ( )
2018-10-30 03:24:18 +00:00
important := infos [ : 0 ]
for _ , info := range infos {
dist := uint64 ( loc . dist ( info . coords ) )
if dist < minDist {
minDist = dist
important = append ( important , info )
}
2018-10-25 03:03:27 +00:00
}
2018-10-30 03:24:18 +00:00
var temp [ ] * dhtInfo
minDist = ^ uint64 ( 0 )
for idx := len ( infos ) - 1 ; idx >= 0 ; idx -- {
info := infos [ idx ]
dist := uint64 ( loc . dist ( info . coords ) )
if dist < minDist {
minDist = dist
temp = append ( temp , info )
}
}
for idx := len ( temp ) - 1 ; idx >= 0 ; idx -- {
important = append ( important , temp [ idx ] )
}
t . imp = important
2018-10-25 03:03:27 +00:00
}
2018-10-30 03:24:18 +00:00
return t . imp
2018-10-21 22:40:43 +00:00
}
2018-11-10 05:02:38 +00:00
// Returns true if this is a node we need to keep track of for the DHT to work.
func ( t * dht ) isImportant ( ninfo * dhtInfo ) bool {
2019-08-24 01:35:54 +00:00
if ninfo . key == t . router . core . boxPub {
2018-11-26 02:33:33 +00:00
return false
}
2018-11-10 05:02:38 +00:00
important := t . getImportant ( )
2018-10-21 22:40:43 +00:00
// Check if ninfo is of equal or greater importance to what we already know
2019-08-24 01:35:54 +00:00
loc := t . router . core . switchTable . getLocator ( )
2018-10-21 22:40:43 +00:00
ndist := uint64 ( loc . dist ( ninfo . coords ) )
minDist := ^ uint64 ( 0 )
for _ , info := range important {
2018-10-25 03:03:27 +00:00
if ( * info . getNodeID ( ) == * ninfo . getNodeID ( ) ) ||
( ndist < minDist && dht_ordered ( info . getNodeID ( ) , ninfo . getNodeID ( ) , & t . nodeID ) ) {
// Either the same node, or a better one
return true
}
2018-10-21 22:40:43 +00:00
dist := uint64 ( loc . dist ( info . coords ) )
if dist < minDist {
minDist = dist
2018-10-21 19:57:04 +00:00
}
2018-10-25 03:03:27 +00:00
}
minDist = ^ uint64 ( 0 )
for idx := len ( important ) - 1 ; idx >= 0 ; idx -- {
info := important [ idx ]
if ( * info . getNodeID ( ) == * ninfo . getNodeID ( ) ) ||
( ndist < minDist && dht_ordered ( & t . nodeID , ninfo . getNodeID ( ) , info . getNodeID ( ) ) ) {
// Either the same node, or a better one
2018-10-21 19:57:04 +00:00
return true
2018-10-21 03:06:36 +00:00
}
2018-10-25 03:03:27 +00:00
dist := uint64 ( loc . dist ( info . coords ) )
if dist < minDist {
minDist = dist
}
2018-03-10 21:16:39 +00:00
}
2018-10-21 22:40:43 +00:00
// We didn't find any important node that ninfo is better than
2018-10-21 19:57:04 +00:00
return false
2018-03-10 21:16:39 +00:00
}