Skip to content

Instantly share code, notes, and snippets.

@brianoflondon
Last active March 21, 2022 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianoflondon/2592efe34500a2481841fa86b7edd391 to your computer and use it in GitHub Desktop.
Save brianoflondon/2592efe34500a2481841fa86b7edd391 to your computer and use it in GitHub Desktop.
import base64
import logging
import os
from typing import Optional
import base64
from timeit import default_timer as timer
import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from single_source import get_version
app = FastAPI(
title="Voltage response API",
description=f"Auto Unlocks a Voltage node",
version="1.0.0",
)
load_dotenv()
VOLTAGE_SECRET = os.getenv("VOLTAGE_SECRET")
VOLTAGE_WALLET_PASSWORD = os.getenv("VOLTAGE_WALLET_PASSWORD")
VOLTAGE_API_KEY = os.getenv("VOLTAGE_API_KEY")
NEXT_API_SERVER_URL = os.getenv("NEXT_API_SERVER_URL")
class VWDetails(BaseModel):
status: Optional[str]
update_available: Optional[bool]
lnd_version: Optional[str]
volt_version: Optional[str]
class VoltageWebhook(BaseModel):
type: str
details: VWDetails
api: str
class VoltageWalletUnlock(BaseModel):
wallet_password: str = VOLTAGE_WALLET_PASSWORD
stateless_init: bool = True
@app.post("/voltage/webhook")
async def voltage_webhook(data: VoltageWebhook, request: Request):
logging.info("Webhook call incoming")
logging.info(data.api)
logging.info(data)
voltage_secret = request.headers.get("VOLTAGE_SECRET")
if not voltage_secret == VOLTAGE_SECRET:
logging.info("Incorrect Secret")
raise HTTPException(status_code=401, detail={"message": "incorrect secret"})
if data.details.status == "stopped":
logging.info("Node is stopped, trying to restart it")
url = "https://api.voltage.cloud/node"
headers = {"X-VOLTAGE-AUTH": VOLTAGE_API_KEY}
async with httpx.AsyncClient(headers=headers) as client:
response = await client.get(url=url, timeout=3)
if response.status_code == 200 and response.json()["nodes"]:
for node in response.json()["nodes"]:
if (
node.get("api_endpoint") == data.api
and node.get("status") == "stopped"
):
logging.info(f"Restarting Node: {node.get('node_name')}")
url = "https://api.voltage.cloud/node/start"
post_data = {"node_id": node.get("node_id")}
response = await client.post(
url=url, json=post_data, timeout=300
)
logging.info(f"Node Start response: {response.json()}")
else:
logging.info(f"Node already running: {node.get('node_name')}")
if data.details.status == "waiting_unlock":
logging.info("Waiting to unlock")
url = f"{NEXT_API_SERVER_URL}v1/unlockwallet"
body = VoltageWalletUnlock()
body.wallet_password = base64.b64encode((body.wallet_password).encode())
ans = {}
locked = True
while locked:
try:
async with httpx.AsyncClient() as client:
response = await client.post(url=url, data=body.json(), timeout=300)
logging.info(response.status_code)
if response.status_code == 200:
locked = False
logging.info("Wallet unlocked successfully")
else:
logging.info(response.json())
raise HTTPException(
status_code=response.status_code, detail=response.json()
)
except httpx.TimeoutException as ex:
logging.warning(f"Timeout error {ex} {ex.__class__}")
except Exception as ex:
ans["onward_response"] = f"{ex.__class__.__name__}"
ans["message"] = "problem unlocking wallet"
raise HTTPException(status_code=408, detail=ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment