def check_steam_key(key): try: PrivateKey(key).pubkey except (ValueError, AssertionError): return False return True
def appendWif(self, wif): if wif: try: PrivateKey(wif) self.wifs.append(wif) except: raise InvalidKeyFormat
def reset_password(self, request): password = request.data.get('password') wif = request.data.get('wif') try: # HACK Пока приходится чекать в базе тк. нет фикса от голоса # rpc = BaseUpdater('golos').rpc # username = rpc.wallet.getAccountFromPrivateKey(wif) db = BlockChainDB() pubkey = PrivateKey(wif).pubkey username = db.get_user_by_posting_key(pubkey).lower() except (ValueError, AssertionError, AttributeError): raise ValidationError('Невалидный постинг ключ') try: user = UserBlockChain.on_bc.get(username=username).user except ObjectDoesNotExist: raise ValidationError('Пользователь не зарегистрирован') if '_unactivated' in user.username: raise ValidationError('Пользователь не зарегистрирован') user.set_password(password) user.save() return Response(user.username)
def validate_wif(self, data): try: PrivateKey(data).pubkey except (ValueError, AssertionError): raise serializers.ValidationError('Невалидный постинг ключ') return data
def decrypt_wif(self, encwif): """ decrypt a wif key """ try: # Try to decode as wif PrivateKey(encwif) return encwif except: pass self.unlock() return format(bip38.decrypt(encwif, self.masterpassword), "wif")
def register_existing_user(request): slz = ExistUserRegiserSerializer(data=request.data) if slz.is_valid(): db = BlockChainDB() wif = slz.validated_data['wif'] mapala_username = slz.validated_data['username'] username = db.get_user_by_posting_key(PrivateKey(wif).pubkey) if username is None: return Response('User with this key not exists', status.HTTP_404_NOT_FOUND) existng_bc = UserBlockChain.on_bc.filter(username=username) if existng_bc.exists(): user = existng_bc.first().user if '_unactivated' in user.username: user.username = mapala_username user.set_password(request.data.get('password')) user.save() else: return Response( 'Mapala user with this key already exists: %s' % user.username, status.HTTP_400_BAD_REQUEST) else: user = User.objects.create_user( username=mapala_username, password=request.data.get('password')) UserBlockChain.objects.create(username=username, user=user, blockchain=BlockChain.current()) # Хук для создания юзера на альфе requests.get('http://alfa.mapala.net/api/v1/site/create_user?user=%s' % mapala_username) logger.info('Registration {} from {}'.format(username, get_client_ip(request))) return Response(jwt_response_by_user(user)) else: return Response(slz._errors, status=status.HTTP_400_BAD_REQUEST)
def addPrivateKey(self, wif): """ Add a private key to the wallet database """ # it could be either graphenebase or pistonbase so we can't check the type directly if isinstance(wif, PrivateKey) or isinstance(wif, GraphenePrivateKey): wif = str(wif) try: pub = format(PrivateKey(wif).pubkey, self.prefix) except: raise InvalidWifError( "Invalid Private Key Format. Please use WIF!") if self.keyStorage: # Test if wallet exists if not self.created(): self.newWallet() self.keyStorage.add(self.encrypt_wif(wif), pub)
def setKeys(self, loadkeys): """ This method is strictly only for in memory keys that are passed to Wallet/Steem with the ``keys`` argument """ log.debug( "Force setting of private keys. Not using the wallet database!") if isinstance(loadkeys, dict): Wallet.keyMap = loadkeys loadkeys = list(loadkeys.values()) elif not isinstance(loadkeys, list): loadkeys = [loadkeys] for wif in loadkeys: try: key = PrivateKey(wif) except: raise InvalidWifError Wallet.keys[format(key.pubkey, self.prefix)] = str(key)
def test_Vote(self): op = operations.Vote( **{ "voter": "foobara", "author": "foobarc", "permlink": "foobard", "weight": 1000 }) ops = [operations.Operation(op)] tx = Signed_Transaction(ref_block_num=ref_block_num, ref_block_prefix=ref_block_prefix, expiration=expiration, operations=ops) tx = tx.sign([wif]) tx.verify([PrivateKey(wif).pubkey]) txWire = hexlify(bytes(tx)).decode("ascii") compare = ("f68585abf4dce7c80457010007666f6f6261726107666f6f62617263" "07666f6f62617264e8030001202e09123f732a438ef6d6138484d7ad" "edfdcf4a4f3d171f7fcafe836efa2a3c8877290bd34c67eded824ac0" "cc39e33d154d0617f64af936a83c442f62aef08fec") self.assertEqual(compare[:-130], txWire[:-130])
def create(self, request): """ Блокчейна привязывается к аккаунту только один раз. Отвязать блокчейн от аккаунта или привязать к другому невозможно. """ # TODO Поменять логику работы с поспами и их авторами.(ТЗ v2) wif = request.data.get('wif', '<non_valid>') try: # HACK не валидируем юзера в бч тк не исправили баг на голосе # rpc = BaseUpdater('golos').rpc # username = rpc.wallet.getAccountFromPrivateKey(wif).lower() # except (ValueError, AssertionError, AttributeError): db = BlockChainDB() pubkey = PrivateKey(wif).pubkey username = db.get_user_by_posting_key(pubkey).lower() except (ValueError, AssertionError, AttributeError): raise ValidationError('Invalid posting key') bc_by_user = UserBlockChain.on_bc.filter(user=request.user).first() if bc_by_user is not None: if username != bc_by_user.username: return Response( 'You already have account: %s, set key for it' % bc_by_user.username, status.HTTP_400_BAD_REQUEST) return Response(self.serializer_class(bc_by_user).data) user_bc = UserBlockChain.on_bc.filter(username=username).first() if user_bc is not None: user = user_bc.user # тут проверка на uncativated if user != request.user: if '_unactivated' in user.username: # TODO Удалять промежуточных юзеров # Меняем автора с промежуточного юзера на текущего. Page.objects.filter(author=user_bc.user).update( author=request.user) Comment.objects.filter(author=user_bc.user).update( author=request.user) user_bc.user = request.user user_bc.save() return Response(self.serializer_class(bc_by_user).data) else: return Response( 'user with this key exists: %s' % user.username, status.HTTP_400_BAD_REQUEST) else: return Response(self.serializer_class(user_bc).data) user_bc = UserBlockChain.objects.create( user=request.user, username=username, blockchain=BlockChain.current()) return Response(self.serializer_class(user_bc).data)
def getAccountFromPrivateKey(self, wif): """ Obtain account name from private key """ pub = format(PrivateKey(wif).pubkey, self.prefix) return self.getAccountFromPublicKey(pub)
def encrypt_wif(self, wif): """ Encrypt a wif key """ self.unlock() return format(bip38.encrypt(PrivateKey(wif), self.masterpassword), "encwif")