Line data Source code
1 : #include "fd_chacha20rng.h" 2 : 3 : FD_FN_CONST ulong 4 3 : fd_chacha20rng_align( void ) { 5 3 : return alignof(fd_chacha20rng_t); 6 3 : } 7 : 8 : FD_FN_CONST ulong 9 3 : fd_chacha20rng_footprint( void ) { 10 3 : return sizeof(fd_chacha20rng_t); 11 3 : } 12 : 13 : void * 14 319887 : fd_chacha20rng_new( void * shmem, int mode ) { 15 319887 : if( FD_UNLIKELY( !shmem ) ) { 16 0 : FD_LOG_WARNING(( "NULL shmem" )); 17 0 : return NULL; 18 0 : } 19 319887 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shmem, alignof(fd_chacha20rng_t) ) ) ) { 20 0 : FD_LOG_WARNING(( "misaligned shmem" )); 21 0 : return NULL; 22 0 : } 23 319887 : memset( shmem, 0, sizeof(fd_chacha20rng_t) ); 24 319887 : if( FD_UNLIKELY( (mode!=FD_CHACHA20RNG_MODE_MOD) & (mode!=FD_CHACHA20RNG_MODE_SHIFT) ) ) { 25 0 : FD_LOG_WARNING(( "invalid mode" )); 26 0 : return NULL; 27 0 : } 28 319887 : ((fd_chacha20rng_t *)shmem)->mode = mode; 29 : 30 319887 : return shmem; 31 319887 : } 32 : 33 : fd_chacha20rng_t * 34 319887 : fd_chacha20rng_join( void * shrng ) { 35 319887 : if( FD_UNLIKELY( !shrng ) ) { 36 0 : FD_LOG_WARNING(( "NULL shrng" )); 37 0 : return NULL; 38 0 : } 39 319887 : return (fd_chacha20rng_t *)shrng; 40 319887 : } 41 : 42 : void * 43 319791 : fd_chacha20rng_leave( fd_chacha20rng_t * rng ) { 44 319791 : if( FD_UNLIKELY( !rng ) ) { 45 0 : FD_LOG_WARNING(( "NULL rng" )); 46 0 : return NULL; 47 0 : } 48 319791 : return (void *)rng; 49 319791 : } 50 : 51 : void * 52 319791 : fd_chacha20rng_delete( void * shrng ) { 53 319791 : if( FD_UNLIKELY( !shrng ) ) { 54 0 : FD_LOG_WARNING(( "NULL shrng" )); 55 0 : return NULL; 56 0 : } 57 319791 : memset( shrng, 0, sizeof(fd_chacha20rng_t) ); 58 319791 : return shrng; 59 319791 : } 60 : 61 : fd_chacha20rng_t * 62 : fd_chacha20rng_init( fd_chacha20rng_t * rng, 63 4513698 : void const * key ) { 64 4513698 : memcpy( rng->key, key, FD_CHACHA20_KEY_SZ ); 65 4513698 : rng->buf_off = 0UL; 66 4513698 : rng->buf_fill = 0UL; 67 4513698 : fd_chacha20rng_private_refill( rng ); 68 4513698 : return rng; 69 4513698 : } 70 : 71 : #if FD_HAS_AVX 72 : 73 : void 74 : fd_chacha20rng_refill_avx( fd_chacha20rng_t * rng ); 75 : 76 : #else 77 : 78 : void 79 : fd_chacha20rng_refill_seq( fd_chacha20rng_t * rng ) { 80 : ulong fill_target = FD_CHACHA20RNG_BUFSZ - FD_CHACHA20_BLOCK_SZ; 81 : 82 : ulong buf_avail; 83 : while( (buf_avail=(rng->buf_fill - rng->buf_off))<fill_target ) { 84 : ulong idx = rng->buf_fill >> 6; 85 : uint idx_nonce[4] __attribute__((aligned(16))) = 86 : { (uint)idx, 0U, 0U, 0U }; 87 : fd_chacha20_block( rng->buf + (rng->buf_fill % FD_CHACHA20RNG_BUFSZ), 88 : rng->key, 89 : idx_nonce ); 90 : rng->buf_fill += (uint)FD_CHACHA20_BLOCK_SZ; 91 : } 92 : } 93 : 94 : #endif