From 0cc3fc24a76c5080eb8149032e22a8da1cc22e5d Mon Sep 17 00:00:00 2001 From: Alex Stokes Date: Thu, 22 Aug 2019 17:55:05 +0200 Subject: [PATCH] Add source for some secure bytes, e.g. to provide a nonce --- libp2p/security/base_transport.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/libp2p/security/base_transport.py b/libp2p/security/base_transport.py index 0f096bf..10d7b66 100644 --- a/libp2p/security/base_transport.py +++ b/libp2p/security/base_transport.py @@ -1,14 +1,30 @@ +import secrets +from typing import Callable + from libp2p.crypto.keys import KeyPair from libp2p.peer.id import ID from libp2p.security.secure_transport_interface import ISecureTransport +def default_secure_bytes_provider(n: int) -> bytes: + return secrets.token_bytes(n) + + class BaseSecureTransport(ISecureTransport): """ ``BaseSecureTransport`` is not fully instantiated from its abstract classes as it is only meant to be used in clases that derive from it. + + Clients can provide a strategy to get cryptographically secure bytes of a given length. + A default implementation is provided using the ``secrets`` module from the + standard library. """ - def __init__(self, local_key_pair: KeyPair) -> None: + def __init__( + self, + local_key_pair: KeyPair, + secure_bytes_provider: Callable[[int], bytes] = default_secure_bytes_provider, + ) -> None: self.local_private_key = local_key_pair.private_key self.local_peer = ID.from_pubkey(local_key_pair.public_key) + self.secure_bytes_provider = secure_bytes_provider