A function that bootstraps a given Kademlia DHT to satisfy the IPFS router interface and connects to all the bootstrap peers provided by libp2p
(ctx context.Context, nodehost host.Host, kaddht *dht.IpfsDHT)
| 370 | // A function that bootstraps a given Kademlia DHT to satisfy the IPFS router |
| 371 | // interface and connects to all the bootstrap peers provided by libp2p |
| 372 | func bootstrapDHT(ctx context.Context, nodehost host.Host, kaddht *dht.IpfsDHT) { |
| 373 | // Bootstrap the DHT to satisfy the IPFS Router interface |
| 374 | if err := kaddht.Bootstrap(ctx); err != nil { |
| 375 | logrus.WithFields(logrus.Fields{ |
| 376 | "error": err.Error(), |
| 377 | }).Fatalln("Failed to Bootstrap the Kademlia!") |
| 378 | } |
| 379 | |
| 380 | // Trace log |
| 381 | logrus.Traceln("Set the Kademlia DHT into Bootstrap Mode.") |
| 382 | |
| 383 | // Declare a WaitGroup |
| 384 | var wg sync.WaitGroup |
| 385 | // Declare counters for the number of bootstrap peers |
| 386 | var connectedbootpeers int32 |
| 387 | var totalbootpeers int32 |
| 388 | |
| 389 | // Iterate over the default bootstrap peers provided by libp2p |
| 390 | for _, peeraddr := range dht.DefaultBootstrapPeers { |
| 391 | // Retrieve the peer address information |
| 392 | peerinfo, _ := peer.AddrInfoFromP2pAddr(peeraddr) |
| 393 | |
| 394 | // Incremenent waitgroup counter |
| 395 | wg.Add(1) |
| 396 | totalbootpeers++ |
| 397 | // Start a goroutine to connect to each bootstrap peer |
| 398 | go func() { |
| 399 | // Defer the waitgroup decrement |
| 400 | defer wg.Done() |
| 401 | // Attempt to connect to the bootstrap peer |
| 402 | if err := nodehost.Connect(ctx, *peerinfo); err == nil { |
| 403 | // Increment the connected bootstrap peer count |
| 404 | atomic.AddInt32(&connectedbootpeers, 1) |
| 405 | // log.Println("Connected bootstrap peer success.", peerinfo.ID, peerinfo) |
| 406 | } |
| 407 | }() |
| 408 | } |
| 409 | |
| 410 | // Wait for the waitgroup to complete |
| 411 | wg.Wait() |
| 412 | |
| 413 | // Log the number of bootstrap peers connected |
| 414 | logrus.Debugf("Connected to %d out of %d Bootstrap Peers.", connectedbootpeers, totalbootpeers) |
| 415 | } |
| 416 | |
| 417 | // A function that connects the given host to all peers received from a |
| 418 | // channel of peer address information. Meant to be started as a go routine. |