sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
bytedance/deer-flow:backend/src/subagents/executor.py | """Subagent execution engine."""
import asyncio
import logging
import threading
import uuid
from concurrent.futures import Future, ThreadPoolExecutor
from concurrent.futures import TimeoutError as FuturesTimeoutError
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Any
from langchain.agents import create_agent
from langchain.tools import BaseTool
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.runnables import RunnableConfig
from src.agents.thread_state import SandboxState, ThreadDataState, ThreadState
from src.models import create_chat_model
from src.subagents.config import SubagentConfig
logger = logging.getLogger(__name__)
class SubagentStatus(Enum):
"""Status of a subagent execution."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
TIMED_OUT = "timed_out"
@dataclass
class SubagentResult:
"""Result of a subagent execution.
Attributes:
task_id: Unique identifier for this execution.
trace_id: Trace ID for distributed tracing (links parent and subagent logs).
status: Current status of the execution.
result: The final result message (if completed).
error: Error message (if failed).
started_at: When execution started.
completed_at: When execution completed.
ai_messages: List of complete AI messages (as dicts) generated during execution.
"""
task_id: str
trace_id: str
status: SubagentStatus
result: str | None = None
error: str | None = None
started_at: datetime | None = None
completed_at: datetime | None = None
ai_messages: list[dict[str, Any]] | None = None
def __post_init__(self):
"""Initialize mutable defaults."""
if self.ai_messages is None:
self.ai_messages = []
# Global storage for background task results
_background_tasks: dict[str, SubagentResult] = {}
_background_tasks_lock = threading.Lock()
# Thread pool for background task scheduling and orchestration
_scheduler_pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix="subagent-scheduler-")
# Thread pool for actual subagent execution (with timeout support)
# Larger pool to avoid blocking when scheduler submits execution tasks
_execution_pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix="subagent-exec-")
def _filter_tools(
all_tools: list[BaseTool],
allowed: list[str] | None,
disallowed: list[str] | None,
) -> list[BaseTool]:
"""Filter tools based on subagent configuration.
Args:
all_tools: List of all available tools.
allowed: Optional allowlist of tool names. If provided, only these tools are included.
disallowed: Optional denylist of tool names. These tools are always excluded.
Returns:
Filtered list of tools.
"""
filtered = all_tools
# Apply allowlist if specified
if allowed is not None:
allowed_set = set(allowed)
filtered = [t for t in filtered if t.name in allowed_set]
# Apply denylist
if disallowed is not None:
disallowed_set = set(disallowed)
filtered = [t for t in filtered if t.name not in disallowed_set]
return filtered
def _get_model_name(config: SubagentConfig, parent_model: str | None) -> str | None:
"""Resolve the model name for a subagent.
Args:
config: Subagent configuration.
parent_model: The parent agent's model name.
Returns:
Model name to use, or None to use default.
"""
if config.model == "inherit":
return parent_model
return config.model
class SubagentExecutor:
"""Executor for running subagents."""
def __init__(
self,
config: SubagentConfig,
tools: list[BaseTool],
parent_model: str | None = None,
sandbox_state: SandboxState | None = None,
thread_data: ThreadDataState | None = None,
thread_id: str | None = None,
trace_id: str | None = None,
):
"""Initialize the executor.
Args:
config: Subagent configuration.
tools: List of all available tools (will be filtered).
parent_model: The parent agent's model name for inheritance.
sandbox_state: Sandbox state from parent agent.
thread_data: Thread data from parent agent.
thread_id: Thread ID for sandbox operations.
trace_id: Trace ID from parent for distributed tracing.
"""
self.config = config
self.parent_model = parent_model
self.sandbox_state = sandbox_state
self.thread_data = thread_data
self.thread_id = thread_id
# Generate trace_id if not provided (for top-level calls)
self.trace_id = trace_id or str(uuid.uuid4())[:8]
# Filter tools based on config
self.tools = _filter_tools(
tools,
config.tools,
config.disallowed_tools,
)
logger.info(f"[trace={self.trace_id}] SubagentExecutor initialized: {config.name} with {len(self.tools)} tools")
def _create_agent(self):
"""Create the agent instance."""
model_name = _get_model_name(self.config, self.parent_model)
model = create_chat_model(name=model_name, thinking_enabled=False)
# Subagents need minimal middlewares to ensure tools can access sandbox and thread_data
# These middlewares will reuse the sandbox/thread_data from parent agent
from src.agents.middlewares.thread_data_middleware import ThreadDataMiddleware
from src.sandbox.middleware import SandboxMiddleware
middlewares = [
ThreadDataMiddleware(lazy_init=True), # Compute thread paths
SandboxMiddleware(lazy_init=True), # Reuse parent's sandbox (no re-acquisition)
]
return create_agent(
model=model,
tools=self.tools,
middleware=middlewares,
system_prompt=self.config.system_prompt,
state_schema=ThreadState,
)
def _build_initial_state(self, task: str) -> dict[str, Any]:
"""Build the initial state for agent execution.
Args:
task: The task description.
Returns:
Initial state dictionary.
"""
state: dict[str, Any] = {
"messages": [HumanMessage(content=task)],
}
# Pass through sandbox and thread data from parent
if self.sandbox_state is not None:
state["sandbox"] = self.sandbox_state
if self.thread_data is not None:
state["thread_data"] = self.thread_data
return state
async def _aexecute(self, task: str, result_holder: SubagentResult | None = None) -> SubagentResult:
"""Execute a task asynchronously.
Args:
task: The task description for the subagent.
result_holder: Optional pre-created result object to update during execution.
Returns:
SubagentResult with the execution result.
"""
if result_holder is not None:
# Use the provided result holder (for async execution with real-time updates)
result = result_holder
else:
# Create a new result for synchronous execution
task_id = str(uuid.uuid4())[:8]
result = SubagentResult(
task_id=task_id,
trace_id=self.trace_id,
status=SubagentStatus.RUNNING,
started_at=datetime.now(),
)
try:
agent = self._create_agent()
state = self._build_initial_state(task)
# Build config with thread_id for sandbox access and recursion limit
run_config: RunnableConfig = {
"recursion_limit": self.config.max_turns,
}
context = {}
if self.thread_id:
run_config["configurable"] = {"thread_id": self.thread_id}
context["thread_id"] = self.thread_id
logger.info(f"[trace={self.trace_id}] Subagent {self.config.name} starting async execution with max_turns={self.config.max_turns}")
# Use stream instead of invoke to get real-time updates
# This allows us to collect AI messages as they are generated
final_state = None
async for chunk in agent.astream(state, config=run_config, context=context, stream_mode="values"): # type: ignore[arg-type]
final_state = chunk
# Extract AI messages from the current state
messages = chunk.get("messages", [])
if messages:
last_message = messages[-1]
# Check if this is a new AI message
if isinstance(last_message, AIMessage):
# Convert message to dict for serialization
message_dict = last_message.model_dump()
# Only add if it's not already in the list (avoid duplicates)
# Check by comparing message IDs if available, otherwise compare full dict
message_id = message_dict.get("id")
is_duplicate = False
if message_id:
is_duplicate = any(msg.get("id") == message_id for msg in result.ai_messages)
else:
is_duplicate = message_dict in result.ai_messages
if not is_duplicate:
result.ai_messages.append(message_dict)
logger.info(f"[trace={self.trace_id}] Subagent {self.config.name} captured AI message #{len(result.ai_messages)}")
logger.info(f"[trace={self.trace_id}] Subagent {self.config.name} completed async execution")
if final_state is None:
logger.warning(f"[trace={self.trace_id}] Subagent {self.config.name} no final state")
result.result = "No response generated"
else:
# Extract the final message - find the last AIMessage
messages = final_state.get("messages", [])
logger.info(f"[trace={self.trace_id}] Subagent {self.config.name} final messages count: {len(messages)}")
# Find the last AIMessage in the conversation
last_ai_message = None
for msg in reversed(messages):
if isinstance(msg, AIMessage):
last_ai_message = msg
break
if last_ai_message is not None:
content = last_ai_message.content
# Handle both str and list content types for the final result
if isinstance(content, str):
result.result = content
elif isinstance(content, list):
# Extract text from list of content blocks for final result only
text_parts = []
for block in content:
if isinstance(block, str):
text_parts.append(block)
elif isinstance(block, dict) and "text" in block:
text_parts.append(block["text"])
result.result = "\n".join(text_parts) if text_parts else "No text content in response"
else:
result.result = str(content)
elif messages:
# Fallback: use the last message if no AIMessage found
last_message = messages[-1]
logger.warning(f"[trace={self.trace_id}] Subagent {self.config.name} no AIMessage found, using last message: {type(last_message)}")
result.result = str(last_message.content) if hasattr(last_message, "content") else str(last_message)
else:
logger.warning(f"[trace={self.trace_id}] Subagent {self.config.name} no messages in final state")
result.result = "No response generated"
result.status = SubagentStatus.COMPLETED
result.completed_at = datetime.now()
except Exception as e:
logger.exception(f"[trace={self.trace_id}] Subagent {self.config.name} async execution failed")
result.status = SubagentStatus.FAILED
result.error = str(e)
result.completed_at = datetime.now()
return result
def execute(self, task: str, result_holder: SubagentResult | None = None) -> SubagentResult:
"""Execute a task synchronously (wrapper around async execution).
This method runs the async execution in a new event loop, allowing
asynchronous tools (like MCP tools) to be used within the thread pool.
Args:
task: The task description for the subagent.
result_holder: Optional pre-created result object to update during execution.
Returns:
SubagentResult with the execution result.
"""
# Run the async execution in a new event loop
# This is necessary because:
# 1. We may have async-only tools (like MCP tools)
# 2. We're running inside a ThreadPoolExecutor which doesn't have an event loop
#
# Note: _aexecute() catches all exceptions internally, so this outer
# try-except only handles asyncio.run() failures (e.g., if called from
# an async context where an event loop already exists). Subagent execution
# errors are handled within _aexecute() and returned as FAILED status.
try:
return asyncio.run(self._aexecute(task, result_holder))
except Exception as e:
logger.exception(f"[trace={self.trace_id}] Subagent {self.config.name} execution failed")
# Create a result with error if we don't have one
if result_holder is not None:
result = result_holder
else:
result = SubagentResult(
task_id=str(uuid.uuid4())[:8],
trace_id=self.trace_id,
status=SubagentStatus.FAILED,
)
result.status = SubagentStatus.FAILED
result.error = str(e)
result.completed_at = datetime.now()
return result
def execute_async(self, task: str, task_id: str | None = None) -> str:
"""Start a task execution in the background.
Args:
task: The task description for the subagent.
task_id: Optional task ID to use. If not provided, a random UUID will be generated.
Returns:
Task ID that can be used to check status later.
"""
# Use provided task_id or generate a new one
if task_id is None:
task_id = str(uuid.uuid4())[:8]
# Create initial pending result
result = SubagentResult(
task_id=task_id,
trace_id=self.trace_id,
status=SubagentStatus.PENDING,
)
logger.info(f"[trace={self.trace_id}] Subagent {self.config.name} starting async execution, task_id={task_id}, timeout={self.config.timeout_seconds}s")
with _background_tasks_lock:
_background_tasks[task_id] = result
# Submit to scheduler pool
def run_task():
with _background_tasks_lock:
_background_tasks[task_id].status = SubagentStatus.RUNNING
_background_tasks[task_id].started_at = datetime.now()
result_holder = _background_tasks[task_id]
try:
# Submit execution to execution pool with timeout
# Pass result_holder so execute() can update it in real-time
execution_future: Future = _execution_pool.submit(self.execute, task, result_holder)
try:
# Wait for execution with timeout
exec_result = execution_future.result(timeout=self.config.timeout_seconds)
with _background_tasks_lock:
_background_tasks[task_id].status = exec_result.status
_background_tasks[task_id].result = exec_result.result
_background_tasks[task_id].error = exec_result.error
_background_tasks[task_id].completed_at = datetime.now()
_background_tasks[task_id].ai_messages = exec_result.ai_messages
except FuturesTimeoutError:
logger.error(f"[trace={self.trace_id}] Subagent {self.config.name} execution timed out after {self.config.timeout_seconds}s")
with _background_tasks_lock:
_background_tasks[task_id].status = SubagentStatus.TIMED_OUT
_background_tasks[task_id].error = f"Execution timed out after {self.config.timeout_seconds} seconds"
_background_tasks[task_id].completed_at = datetime.now()
# Cancel the future (best effort - may not stop the actual execution)
execution_future.cancel()
except Exception as e:
logger.exception(f"[trace={self.trace_id}] Subagent {self.config.name} async execution failed")
with _background_tasks_lock:
_background_tasks[task_id].status = SubagentStatus.FAILED
_background_tasks[task_id].error = str(e)
_background_tasks[task_id].completed_at = datetime.now()
_scheduler_pool.submit(run_task)
return task_id
MAX_CONCURRENT_SUBAGENTS = 3
def get_background_task_result(task_id: str) -> SubagentResult | None:
"""Get the result of a background task.
Args:
task_id: The task ID returned by execute_async.
Returns:
SubagentResult if found, None otherwise.
"""
with _background_tasks_lock:
return _background_tasks.get(task_id)
def list_background_tasks() -> list[SubagentResult]:
"""List all background tasks.
Returns:
List of all SubagentResult instances.
"""
with _background_tasks_lock:
return list(_background_tasks.values())
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/subagents/executor.py",
"license": "MIT License",
"lines": 374,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:backend/src/subagents/registry.py | """Subagent registry for managing available subagents."""
import logging
from dataclasses import replace
from src.subagents.builtins import BUILTIN_SUBAGENTS
from src.subagents.config import SubagentConfig
logger = logging.getLogger(__name__)
def get_subagent_config(name: str) -> SubagentConfig | None:
"""Get a subagent configuration by name, with config.yaml overrides applied.
Args:
name: The name of the subagent.
Returns:
SubagentConfig if found (with any config.yaml overrides applied), None otherwise.
"""
config = BUILTIN_SUBAGENTS.get(name)
if config is None:
return None
# Apply timeout override from config.yaml (lazy import to avoid circular deps)
from src.config.subagents_config import get_subagents_app_config
app_config = get_subagents_app_config()
effective_timeout = app_config.get_timeout_for(name)
if effective_timeout != config.timeout_seconds:
logger.debug(f"Subagent '{name}': timeout overridden by config.yaml ({config.timeout_seconds}s -> {effective_timeout}s)")
config = replace(config, timeout_seconds=effective_timeout)
return config
def list_subagents() -> list[SubagentConfig]:
"""List all available subagent configurations (with config.yaml overrides applied).
Returns:
List of all registered SubagentConfig instances.
"""
return [get_subagent_config(name) for name in BUILTIN_SUBAGENTS]
def get_subagent_names() -> list[str]:
"""Get all available subagent names.
Returns:
List of subagent names.
"""
return list(BUILTIN_SUBAGENTS.keys())
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/subagents/registry.py",
"license": "MIT License",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
bytedance/deer-flow:backend/src/tools/builtins/clarification_tool.py | from typing import Literal
from langchain.tools import tool
@tool("ask_clarification", parse_docstring=True, return_direct=True)
def ask_clarification_tool(
question: str,
clarification_type: Literal[
"missing_info",
"ambiguous_requirement",
"approach_choice",
"risk_confirmation",
"suggestion",
],
context: str | None = None,
options: list[str] | None = None,
) -> str:
"""Ask the user for clarification when you need more information to proceed.
Use this tool when you encounter situations where you cannot proceed without user input:
- **Missing information**: Required details not provided (e.g., file paths, URLs, specific requirements)
- **Ambiguous requirements**: Multiple valid interpretations exist
- **Approach choices**: Several valid approaches exist and you need user preference
- **Risky operations**: Destructive actions that need explicit confirmation (e.g., deleting files, modifying production)
- **Suggestions**: You have a recommendation but want user approval before proceeding
The execution will be interrupted and the question will be presented to the user.
Wait for the user's response before continuing.
When to use ask_clarification:
- You need information that wasn't provided in the user's request
- The requirement can be interpreted in multiple ways
- Multiple valid implementation approaches exist
- You're about to perform a potentially dangerous operation
- You have a recommendation but need user approval
Best practices:
- Ask ONE clarification at a time for clarity
- Be specific and clear in your question
- Don't make assumptions when clarification is needed
- For risky operations, ALWAYS ask for confirmation
- After calling this tool, execution will be interrupted automatically
Args:
question: The clarification question to ask the user. Be specific and clear.
clarification_type: The type of clarification needed (missing_info, ambiguous_requirement, approach_choice, risk_confirmation, suggestion).
context: Optional context explaining why clarification is needed. Helps the user understand the situation.
options: Optional list of choices (for approach_choice or suggestion types). Present clear options for the user to choose from.
"""
# This is a placeholder implementation
# The actual logic is handled by ClarificationMiddleware which intercepts this tool call
# and interrupts execution to present the question to the user
return "Clarification request processed by middleware"
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/tools/builtins/clarification_tool.py",
"license": "MIT License",
"lines": 46,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
bytedance/deer-flow:backend/src/tools/builtins/present_file_tool.py | from pathlib import Path
from typing import Annotated
from langchain.tools import InjectedToolCallId, ToolRuntime, tool
from langchain_core.messages import ToolMessage
from langgraph.types import Command
from langgraph.typing import ContextT
from src.agents.thread_state import ThreadState
from src.config.paths import VIRTUAL_PATH_PREFIX, get_paths
OUTPUTS_VIRTUAL_PREFIX = f"{VIRTUAL_PATH_PREFIX}/outputs"
def _normalize_presented_filepath(
runtime: ToolRuntime[ContextT, ThreadState],
filepath: str,
) -> str:
"""Normalize a presented file path to the `/mnt/user-data/outputs/*` contract.
Accepts either:
- A virtual sandbox path such as `/mnt/user-data/outputs/report.md`
- A host-side thread outputs path such as
`/app/backend/.deer-flow/threads/<thread>/user-data/outputs/report.md`
Returns:
The normalized virtual path.
Raises:
ValueError: If runtime metadata is missing or the path is outside the
current thread's outputs directory.
"""
if runtime.state is None:
raise ValueError("Thread runtime state is not available")
thread_id = runtime.context.get("thread_id")
if not thread_id:
raise ValueError("Thread ID is not available in runtime context")
thread_data = runtime.state.get("thread_data") or {}
outputs_path = thread_data.get("outputs_path")
if not outputs_path:
raise ValueError("Thread outputs path is not available in runtime state")
outputs_dir = Path(outputs_path).resolve()
stripped = filepath.lstrip("/")
virtual_prefix = VIRTUAL_PATH_PREFIX.lstrip("/")
if stripped == virtual_prefix or stripped.startswith(virtual_prefix + "/"):
actual_path = get_paths().resolve_virtual_path(thread_id, filepath)
else:
actual_path = Path(filepath).expanduser().resolve()
try:
relative_path = actual_path.relative_to(outputs_dir)
except ValueError as exc:
raise ValueError(
f"Only files in {OUTPUTS_VIRTUAL_PREFIX} can be presented: {filepath}"
) from exc
return f"{OUTPUTS_VIRTUAL_PREFIX}/{relative_path.as_posix()}"
@tool("present_files", parse_docstring=True)
def present_file_tool(
runtime: ToolRuntime[ContextT, ThreadState],
filepaths: list[str],
tool_call_id: Annotated[str, InjectedToolCallId],
) -> Command:
"""Make files visible to the user for viewing and rendering in the client interface.
When to use the present_files tool:
- Making any file available for the user to view, download, or interact with
- Presenting multiple related files at once
- After creating files that should be presented to the user
When NOT to use the present_files tool:
- When you only need to read file contents for your own processing
- For temporary or intermediate files not meant for user viewing
Notes:
- You should call this tool after creating files and moving them to the `/mnt/user-data/outputs` directory.
- This tool can be safely called in parallel with other tools. State updates are handled by a reducer to prevent conflicts.
Args:
filepaths: List of absolute file paths to present to the user. **Only** files in `/mnt/user-data/outputs` can be presented.
"""
try:
normalized_paths = [
_normalize_presented_filepath(runtime, filepath) for filepath in filepaths
]
except ValueError as exc:
return Command(
update={
"messages": [ToolMessage(f"Error: {exc}", tool_call_id=tool_call_id)]
},
)
# The merge_artifacts reducer will handle merging and deduplication
return Command(
update={
"artifacts": normalized_paths,
"messages": [
ToolMessage("Successfully presented files", tool_call_id=tool_call_id)
],
},
)
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/tools/builtins/present_file_tool.py",
"license": "MIT License",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:backend/src/tools/builtins/task_tool.py | """Task tool for delegating work to subagents."""
import logging
import time
import uuid
from dataclasses import replace
from typing import Annotated, Literal
from langchain.tools import InjectedToolCallId, ToolRuntime, tool
from langgraph.config import get_stream_writer
from langgraph.typing import ContextT
from src.agents.lead_agent.prompt import get_skills_prompt_section
from src.agents.thread_state import ThreadState
from src.subagents import SubagentExecutor, get_subagent_config
from src.subagents.executor import SubagentStatus, get_background_task_result
logger = logging.getLogger(__name__)
@tool("task", parse_docstring=True)
def task_tool(
runtime: ToolRuntime[ContextT, ThreadState],
description: str,
prompt: str,
subagent_type: Literal["general-purpose", "bash"],
tool_call_id: Annotated[str, InjectedToolCallId],
max_turns: int | None = None,
) -> str:
"""Delegate a task to a specialized subagent that runs in its own context.
Subagents help you:
- Preserve context by keeping exploration and implementation separate
- Handle complex multi-step tasks autonomously
- Execute commands or operations in isolated contexts
Available subagent types:
- **general-purpose**: A capable agent for complex, multi-step tasks that require
both exploration and action. Use when the task requires complex reasoning,
multiple dependent steps, or would benefit from isolated context.
- **bash**: Command execution specialist for running bash commands. Use for
git operations, build processes, or when command output would be verbose.
When to use this tool:
- Complex tasks requiring multiple steps or tools
- Tasks that produce verbose output
- When you want to isolate context from the main conversation
- Parallel research or exploration tasks
When NOT to use this tool:
- Simple, single-step operations (use tools directly)
- Tasks requiring user interaction or clarification
Args:
description: A short (3-5 word) description of the task for logging/display. ALWAYS PROVIDE THIS PARAMETER FIRST.
prompt: The task description for the subagent. Be specific and clear about what needs to be done. ALWAYS PROVIDE THIS PARAMETER SECOND.
subagent_type: The type of subagent to use. ALWAYS PROVIDE THIS PARAMETER THIRD.
max_turns: Optional maximum number of agent turns. Defaults to subagent's configured max.
"""
# Get subagent configuration
config = get_subagent_config(subagent_type)
if config is None:
return f"Error: Unknown subagent type '{subagent_type}'. Available: general-purpose, bash"
# Build config overrides
overrides: dict = {}
skills_section = get_skills_prompt_section()
if skills_section:
overrides["system_prompt"] = config.system_prompt + "\n\n" + skills_section
if max_turns is not None:
overrides["max_turns"] = max_turns
if overrides:
config = replace(config, **overrides)
# Extract parent context from runtime
sandbox_state = None
thread_data = None
thread_id = None
parent_model = None
trace_id = None
if runtime is not None:
sandbox_state = runtime.state.get("sandbox")
thread_data = runtime.state.get("thread_data")
thread_id = runtime.context.get("thread_id")
# Try to get parent model from configurable
metadata = runtime.config.get("metadata", {})
parent_model = metadata.get("model_name")
# Get or generate trace_id for distributed tracing
trace_id = metadata.get("trace_id") or str(uuid.uuid4())[:8]
# Get available tools (excluding task tool to prevent nesting)
# Lazy import to avoid circular dependency
from src.tools import get_available_tools
# Subagents should not have subagent tools enabled (prevent recursive nesting)
tools = get_available_tools(model_name=parent_model, subagent_enabled=False)
# Create executor
executor = SubagentExecutor(
config=config,
tools=tools,
parent_model=parent_model,
sandbox_state=sandbox_state,
thread_data=thread_data,
thread_id=thread_id,
trace_id=trace_id,
)
# Start background execution (always async to prevent blocking)
# Use tool_call_id as task_id for better traceability
task_id = executor.execute_async(prompt, task_id=tool_call_id)
# Poll for task completion in backend (removes need for LLM to poll)
poll_count = 0
last_status = None
last_message_count = 0 # Track how many AI messages we've already sent
# Polling timeout: execution timeout + 60s buffer, checked every 5s
max_poll_count = (config.timeout_seconds + 60) // 5
logger.info(f"[trace={trace_id}] Started background task {task_id} (subagent={subagent_type}, timeout={config.timeout_seconds}s, polling_limit={max_poll_count} polls)")
writer = get_stream_writer()
# Send Task Started message'
writer({"type": "task_started", "task_id": task_id, "description": description})
while True:
result = get_background_task_result(task_id)
if result is None:
logger.error(f"[trace={trace_id}] Task {task_id} not found in background tasks")
writer({"type": "task_failed", "task_id": task_id, "error": "Task disappeared from background tasks"})
return f"Error: Task {task_id} disappeared from background tasks"
# Log status changes for debugging
if result.status != last_status:
logger.info(f"[trace={trace_id}] Task {task_id} status: {result.status.value}")
last_status = result.status
# Check for new AI messages and send task_running events
current_message_count = len(result.ai_messages)
if current_message_count > last_message_count:
# Send task_running event for each new message
for i in range(last_message_count, current_message_count):
message = result.ai_messages[i]
writer(
{
"type": "task_running",
"task_id": task_id,
"message": message,
"message_index": i + 1, # 1-based index for display
"total_messages": current_message_count,
}
)
logger.info(f"[trace={trace_id}] Task {task_id} sent message #{i + 1}/{current_message_count}")
last_message_count = current_message_count
# Check if task completed, failed, or timed out
if result.status == SubagentStatus.COMPLETED:
writer({"type": "task_completed", "task_id": task_id, "result": result.result})
logger.info(f"[trace={trace_id}] Task {task_id} completed after {poll_count} polls")
return f"Task Succeeded. Result: {result.result}"
elif result.status == SubagentStatus.FAILED:
writer({"type": "task_failed", "task_id": task_id, "error": result.error})
logger.error(f"[trace={trace_id}] Task {task_id} failed: {result.error}")
return f"Task failed. Error: {result.error}"
elif result.status == SubagentStatus.TIMED_OUT:
writer({"type": "task_timed_out", "task_id": task_id, "error": result.error})
logger.warning(f"[trace={trace_id}] Task {task_id} timed out: {result.error}")
return f"Task timed out. Error: {result.error}"
# Still running, wait before next poll
time.sleep(5) # Poll every 5 seconds
poll_count += 1
# Polling timeout as a safety net (in case thread pool timeout doesn't work)
# Set to execution timeout + 60s buffer, in 5s poll intervals
# This catches edge cases where the background task gets stuck
if poll_count > max_poll_count:
timeout_minutes = config.timeout_seconds // 60
logger.error(f"[trace={trace_id}] Task {task_id} polling timed out after {poll_count} polls (should have been caught by thread pool timeout)")
writer({"type": "task_timed_out", "task_id": task_id})
return f"Task polling timed out after {timeout_minutes} minutes. This may indicate the background task is stuck. Status: {result.status.value}"
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/tools/builtins/task_tool.py",
"license": "MIT License",
"lines": 155,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:backend/src/tools/builtins/view_image_tool.py | import base64
import mimetypes
from pathlib import Path
from typing import Annotated
from langchain.tools import InjectedToolCallId, ToolRuntime, tool
from langchain_core.messages import ToolMessage
from langgraph.types import Command
from langgraph.typing import ContextT
from src.agents.thread_state import ThreadState
from src.sandbox.tools import get_thread_data, replace_virtual_path
@tool("view_image", parse_docstring=True)
def view_image_tool(
runtime: ToolRuntime[ContextT, ThreadState],
image_path: str,
tool_call_id: Annotated[str, InjectedToolCallId],
) -> Command:
"""Read an image file.
Use this tool to read an image file and make it available for display.
When to use the view_image tool:
- When you need to view an image file.
When NOT to use the view_image tool:
- For non-image files (use present_files instead)
- For multiple files at once (use present_files instead)
Args:
image_path: Absolute path to the image file. Common formats supported: jpg, jpeg, png, webp.
"""
# Replace virtual path with actual path
# /mnt/user-data/* paths are mapped to thread-specific directories
thread_data = get_thread_data(runtime)
actual_path = replace_virtual_path(image_path, thread_data)
# Validate that the path is absolute
path = Path(actual_path)
if not path.is_absolute():
return Command(
update={"messages": [ToolMessage(f"Error: Path must be absolute, got: {image_path}", tool_call_id=tool_call_id)]},
)
# Validate that the file exists
if not path.exists():
return Command(
update={"messages": [ToolMessage(f"Error: Image file not found: {image_path}", tool_call_id=tool_call_id)]},
)
# Validate that it's a file (not a directory)
if not path.is_file():
return Command(
update={"messages": [ToolMessage(f"Error: Path is not a file: {image_path}", tool_call_id=tool_call_id)]},
)
# Validate image extension
valid_extensions = {".jpg", ".jpeg", ".png", ".webp"}
if path.suffix.lower() not in valid_extensions:
return Command(
update={"messages": [ToolMessage(f"Error: Unsupported image format: {path.suffix}. Supported formats: {', '.join(valid_extensions)}", tool_call_id=tool_call_id)]},
)
# Detect MIME type from file extension
mime_type, _ = mimetypes.guess_type(actual_path)
if mime_type is None:
# Fallback to default MIME types for common image formats
extension_to_mime = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
}
mime_type = extension_to_mime.get(path.suffix.lower(), "application/octet-stream")
# Read image file and convert to base64
try:
with open(actual_path, "rb") as f:
image_data = f.read()
image_base64 = base64.b64encode(image_data).decode("utf-8")
except Exception as e:
return Command(
update={"messages": [ToolMessage(f"Error reading image file: {str(e)}", tool_call_id=tool_call_id)]},
)
# Update viewed_images in state
# The merge_viewed_images reducer will handle merging with existing images
new_viewed_images = {image_path: {"base64": image_base64, "mime_type": mime_type}}
return Command(
update={"viewed_images": new_viewed_images, "messages": [ToolMessage("Successfully read image", tool_call_id=tool_call_id)]},
)
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/tools/builtins/view_image_tool.py",
"license": "MIT License",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
bytedance/deer-flow:backend/src/tools/tools.py | import logging
from langchain.tools import BaseTool
from src.config import get_app_config
from src.reflection import resolve_variable
from src.tools.builtins import ask_clarification_tool, present_file_tool, task_tool, view_image_tool
logger = logging.getLogger(__name__)
BUILTIN_TOOLS = [
present_file_tool,
ask_clarification_tool,
]
SUBAGENT_TOOLS = [
task_tool,
# task_status_tool is no longer exposed to LLM (backend handles polling internally)
]
def get_available_tools(
groups: list[str] | None = None,
include_mcp: bool = True,
model_name: str | None = None,
subagent_enabled: bool = False,
) -> list[BaseTool]:
"""Get all available tools from config.
Note: MCP tools should be initialized at application startup using
`initialize_mcp_tools()` from src.mcp module.
Args:
groups: Optional list of tool groups to filter by.
include_mcp: Whether to include tools from MCP servers (default: True).
model_name: Optional model name to determine if vision tools should be included.
subagent_enabled: Whether to include subagent tools (task, task_status).
Returns:
List of available tools.
"""
config = get_app_config()
loaded_tools = [resolve_variable(tool.use, BaseTool) for tool in config.tools if groups is None or tool.group in groups]
# Get cached MCP tools if enabled
# NOTE: We use ExtensionsConfig.from_file() instead of config.extensions
# to always read the latest configuration from disk. This ensures that changes
# made through the Gateway API (which runs in a separate process) are immediately
# reflected when loading MCP tools.
mcp_tools = []
if include_mcp:
try:
from src.config.extensions_config import ExtensionsConfig
from src.mcp.cache import get_cached_mcp_tools
extensions_config = ExtensionsConfig.from_file()
if extensions_config.get_enabled_mcp_servers():
mcp_tools = get_cached_mcp_tools()
if mcp_tools:
logger.info(f"Using {len(mcp_tools)} cached MCP tool(s)")
except ImportError:
logger.warning("MCP module not available. Install 'langchain-mcp-adapters' package to enable MCP tools.")
except Exception as e:
logger.error(f"Failed to get cached MCP tools: {e}")
# Conditionally add tools based on config
builtin_tools = BUILTIN_TOOLS.copy()
# Add subagent tools only if enabled via runtime parameter
if subagent_enabled:
builtin_tools.extend(SUBAGENT_TOOLS)
logger.info("Including subagent tools (task)")
# If no model_name specified, use the first model (default)
if model_name is None and config.models:
model_name = config.models[0].name
# Add view_image_tool only if the model supports vision
model_config = config.get_model_config(model_name) if model_name else None
if model_config is not None and model_config.supports_vision:
builtin_tools.append(view_image_tool)
logger.info(f"Including view_image_tool for model '{model_name}' (supports_vision=True)")
return loaded_tools + builtin_tools + mcp_tools
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/tools/tools.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:backend/src/utils/network.py | """Thread-safe network utilities."""
import socket
import threading
from contextlib import contextmanager
class PortAllocator:
"""Thread-safe port allocator that prevents port conflicts in concurrent environments.
This class maintains a set of reserved ports and uses a lock to ensure that
port allocation is atomic. Once a port is allocated, it remains reserved until
explicitly released.
Usage:
allocator = PortAllocator()
# Option 1: Manual allocation and release
port = allocator.allocate(start_port=8080)
try:
# Use the port...
finally:
allocator.release(port)
# Option 2: Context manager (recommended)
with allocator.allocate_context(start_port=8080) as port:
# Use the port...
# Port is automatically released when exiting the context
"""
def __init__(self):
self._lock = threading.Lock()
self._reserved_ports: set[int] = set()
def _is_port_available(self, port: int) -> bool:
"""Check if a port is available for binding.
Args:
port: The port number to check.
Returns:
True if the port is available, False otherwise.
"""
if port in self._reserved_ports:
return False
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("localhost", port))
return True
except OSError:
return False
def allocate(self, start_port: int = 8080, max_range: int = 100) -> int:
"""Allocate an available port in a thread-safe manner.
This method is thread-safe. It finds an available port, marks it as reserved,
and returns it. The port remains reserved until release() is called.
Args:
start_port: The port number to start searching from.
max_range: Maximum number of ports to search.
Returns:
An available port number.
Raises:
RuntimeError: If no available port is found in the specified range.
"""
with self._lock:
for port in range(start_port, start_port + max_range):
if self._is_port_available(port):
self._reserved_ports.add(port)
return port
raise RuntimeError(f"No available port found in range {start_port}-{start_port + max_range}")
def release(self, port: int) -> None:
"""Release a previously allocated port.
Args:
port: The port number to release.
"""
with self._lock:
self._reserved_ports.discard(port)
@contextmanager
def allocate_context(self, start_port: int = 8080, max_range: int = 100):
"""Context manager for port allocation with automatic release.
Args:
start_port: The port number to start searching from.
max_range: Maximum number of ports to search.
Yields:
An available port number.
"""
port = self.allocate(start_port, max_range)
try:
yield port
finally:
self.release(port)
# Global port allocator instance for shared use across the application
_global_port_allocator = PortAllocator()
def get_free_port(start_port: int = 8080, max_range: int = 100) -> int:
"""Get a free port in a thread-safe manner.
This function uses a global port allocator to ensure that concurrent calls
don't return the same port. The port is marked as reserved until release_port()
is called.
Args:
start_port: The port number to start searching from.
max_range: Maximum number of ports to search.
Returns:
An available port number.
Raises:
RuntimeError: If no available port is found in the specified range.
"""
return _global_port_allocator.allocate(start_port, max_range)
def release_port(port: int) -> None:
"""Release a previously allocated port.
Args:
port: The port number to release.
"""
_global_port_allocator.release(port)
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/utils/network.py",
"license": "MIT License",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
bytedance/deer-flow:backend/src/utils/readability.py | import logging
import re
import subprocess
from urllib.parse import urljoin
from markdownify import markdownify as md
from readabilipy import simple_json_from_html_string
logger = logging.getLogger(__name__)
class Article:
url: str
def __init__(self, title: str, html_content: str):
self.title = title
self.html_content = html_content
def to_markdown(self, including_title: bool = True) -> str:
markdown = ""
if including_title:
markdown += f"# {self.title}\n\n"
if self.html_content is None or not str(self.html_content).strip():
markdown += "*No content available*\n"
else:
markdown += md(self.html_content)
return markdown
def to_message(self) -> list[dict]:
image_pattern = r"!\[.*?\]\((.*?)\)"
content: list[dict[str, str]] = []
markdown = self.to_markdown()
if not markdown or not markdown.strip():
return [{"type": "text", "text": "No content available"}]
parts = re.split(image_pattern, markdown)
for i, part in enumerate(parts):
if i % 2 == 1:
image_url = urljoin(self.url, part.strip())
content.append({"type": "image_url", "image_url": {"url": image_url}})
else:
text_part = part.strip()
if text_part:
content.append({"type": "text", "text": text_part})
# If after processing all parts, content is still empty, provide a fallback message.
if not content:
content = [{"type": "text", "text": "No content available"}]
return content
class ReadabilityExtractor:
def extract_article(self, html: str) -> Article:
try:
article = simple_json_from_html_string(html, use_readability=True)
except (subprocess.CalledProcessError, FileNotFoundError) as exc:
stderr = getattr(exc, "stderr", None)
if isinstance(stderr, bytes):
stderr = stderr.decode(errors="replace")
stderr_info = f"; stderr={stderr.strip()}" if isinstance(stderr, str) and stderr.strip() else ""
logger.warning(
"Readability.js extraction failed with %s%s; falling back to pure-Python extraction",
type(exc).__name__,
stderr_info,
exc_info=True,
)
article = simple_json_from_html_string(html, use_readability=False)
html_content = article.get("content")
if not html_content or not str(html_content).strip():
html_content = "No content could be extracted from this page"
title = article.get("title")
if not title or not str(title).strip():
title = "Untitled"
return Article(title=title, html_content=html_content)
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/src/utils/readability.py",
"license": "MIT License",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:backend/tests/test_title_generation.py | """Tests for automatic thread title generation."""
import pytest
from src.agents.middlewares.title_middleware import TitleMiddleware
from src.config.title_config import TitleConfig, get_title_config, set_title_config
class TestTitleConfig:
"""Tests for TitleConfig."""
def test_default_config(self):
"""Test default configuration values."""
config = TitleConfig()
assert config.enabled is True
assert config.max_words == 6
assert config.max_chars == 60
assert config.model_name is None
def test_custom_config(self):
"""Test custom configuration."""
config = TitleConfig(
enabled=False,
max_words=10,
max_chars=100,
model_name="gpt-4",
)
assert config.enabled is False
assert config.max_words == 10
assert config.max_chars == 100
assert config.model_name == "gpt-4"
def test_config_validation(self):
"""Test configuration validation."""
# max_words should be between 1 and 20
with pytest.raises(ValueError):
TitleConfig(max_words=0)
with pytest.raises(ValueError):
TitleConfig(max_words=21)
# max_chars should be between 10 and 200
with pytest.raises(ValueError):
TitleConfig(max_chars=5)
with pytest.raises(ValueError):
TitleConfig(max_chars=201)
def test_get_set_config(self):
"""Test global config getter and setter."""
original_config = get_title_config()
# Set new config
new_config = TitleConfig(enabled=False, max_words=10)
set_title_config(new_config)
# Verify it was set
assert get_title_config().enabled is False
assert get_title_config().max_words == 10
# Restore original config
set_title_config(original_config)
class TestTitleMiddleware:
"""Tests for TitleMiddleware."""
def test_middleware_initialization(self):
"""Test middleware can be initialized."""
middleware = TitleMiddleware()
assert middleware is not None
assert middleware.state_schema is not None
# TODO: Add integration tests with mock Runtime
# def test_should_generate_title(self):
# """Test title generation trigger logic."""
# pass
# def test_generate_title(self):
# """Test title generation."""
# pass
# def test_after_agent_hook(self):
# """Test after_agent hook."""
# pass
# TODO: Add integration tests
# - Test with real LangGraph runtime
# - Test title persistence with checkpointer
# - Test fallback behavior when LLM fails
# - Test concurrent title generation
| {
"repo_id": "bytedance/deer-flow",
"file_path": "backend/tests/test_title_generation.py",
"license": "MIT License",
"lines": 70,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
bytedance/deer-flow:docker/provisioner/app.py | """DeerFlow Sandbox Provisioner Service.
Dynamically creates and manages per-sandbox Pods in Kubernetes.
Each ``sandbox_id`` gets its own Pod + NodePort Service. The backend
accesses sandboxes directly via ``{NODE_HOST}:{NodePort}``.
The provisioner connects to the host machine's Kubernetes cluster via a
mounted kubeconfig (``~/.kube/config``). Sandbox Pods run on the host
K8s and are accessed by the backend via ``{NODE_HOST}:{NodePort}``.
Endpoints:
POST /api/sandboxes — Create a sandbox Pod + Service
DELETE /api/sandboxes/{sandbox_id} — Destroy a sandbox Pod + Service
GET /api/sandboxes/{sandbox_id} — Get sandbox status & URL
GET /api/sandboxes — List all sandboxes
GET /health — Provisioner health check
Architecture (docker-compose-dev):
┌────────────┐ HTTP ┌─────────────┐ K8s API ┌──────────────┐
│ remote │ ─────▸ │ provisioner │ ────────▸ │ host K8s │
│ _backend │ │ :8002 │ │ API server │
└────────────┘ └─────────────┘ └──────┬───────┘
│ creates
┌─────────────┐ ┌──────▼───────┐
│ backend │ ────────▸ │ sandbox │
│ │ direct │ Pod(s) │
└─────────────┘ NodePort └──────────────┘
"""
from __future__ import annotations
import logging
import os
import time
from contextlib import asynccontextmanager
import urllib3
from fastapi import FastAPI, HTTPException
from kubernetes import client as k8s_client
from kubernetes import config as k8s_config
from kubernetes.client.rest import ApiException
from pydantic import BaseModel
# Suppress only the InsecureRequestWarning from urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
# ── Configuration (all tuneable via environment variables) ───────────────
K8S_NAMESPACE = os.environ.get("K8S_NAMESPACE", "deer-flow")
SANDBOX_IMAGE = os.environ.get(
"SANDBOX_IMAGE",
"enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest",
)
SKILLS_HOST_PATH = os.environ.get("SKILLS_HOST_PATH", "/skills")
THREADS_HOST_PATH = os.environ.get("THREADS_HOST_PATH", "/.deer-flow/threads")
# Path to the kubeconfig *inside* the provisioner container.
# Typically the host's ~/.kube/config is mounted here.
KUBECONFIG_PATH = os.environ.get("KUBECONFIG_PATH", "/root/.kube/config")
# The hostname / IP that the *backend container* uses to reach NodePort
# services on the host Kubernetes node. On Docker Desktop for macOS this
# is ``host.docker.internal``; on Linux it may be the host's LAN IP.
NODE_HOST = os.environ.get("NODE_HOST", "host.docker.internal")
# ── K8s client setup ────────────────────────────────────────────────────
core_v1: k8s_client.CoreV1Api | None = None
def _init_k8s_client() -> k8s_client.CoreV1Api:
"""Load kubeconfig from the mounted host config and return a CoreV1Api.
Tries the mounted kubeconfig first, then falls back to in-cluster
config (useful if the provisioner itself runs inside K8s).
"""
if os.path.exists(KUBECONFIG_PATH):
if os.path.isdir(KUBECONFIG_PATH):
raise RuntimeError(
f"KUBECONFIG_PATH points to a directory, expected a file: {KUBECONFIG_PATH}"
)
try:
k8s_config.load_kube_config(config_file=KUBECONFIG_PATH)
logger.info(f"Loaded kubeconfig from {KUBECONFIG_PATH}")
except Exception as exc:
raise RuntimeError(
f"Failed to load kubeconfig from {KUBECONFIG_PATH}: {exc}"
) from exc
else:
logger.warning(
f"Kubeconfig not found at {KUBECONFIG_PATH}; trying in-cluster config"
)
try:
k8s_config.load_incluster_config()
except Exception as exc:
raise RuntimeError(
"Failed to initialize Kubernetes client. "
f"No kubeconfig at {KUBECONFIG_PATH}, and in-cluster config is unavailable: {exc}"
) from exc
# When connecting from inside Docker to the host's K8s API, the
# kubeconfig may reference ``localhost`` or ``127.0.0.1``. We
# optionally rewrite the server address so it reaches the host.
k8s_api_server = os.environ.get("K8S_API_SERVER")
if k8s_api_server:
configuration = k8s_client.Configuration.get_default_copy()
configuration.host = k8s_api_server
# Self-signed certs are common for local clusters
configuration.verify_ssl = False
api_client = k8s_client.ApiClient(configuration)
return k8s_client.CoreV1Api(api_client)
return k8s_client.CoreV1Api()
def _wait_for_kubeconfig(timeout: int = 30) -> None:
"""Wait for kubeconfig file if configured, then continue with fallback support."""
deadline = time.time() + timeout
while time.time() < deadline:
if os.path.exists(KUBECONFIG_PATH):
if os.path.isfile(KUBECONFIG_PATH):
logger.info(f"Found kubeconfig file at {KUBECONFIG_PATH}")
return
if os.path.isdir(KUBECONFIG_PATH):
raise RuntimeError(
"Kubeconfig path is a directory. "
f"Please mount a kubeconfig file at {KUBECONFIG_PATH}."
)
raise RuntimeError(
f"Kubeconfig path exists but is not a regular file: {KUBECONFIG_PATH}"
)
logger.info(f"Waiting for kubeconfig at {KUBECONFIG_PATH} …")
time.sleep(2)
logger.warning(
f"Kubeconfig not found at {KUBECONFIG_PATH} after {timeout}s; "
"will attempt in-cluster Kubernetes config"
)
def _ensure_namespace() -> None:
"""Create the K8s namespace if it does not yet exist."""
try:
core_v1.read_namespace(K8S_NAMESPACE)
logger.info(f"Namespace '{K8S_NAMESPACE}' already exists")
except ApiException as exc:
if exc.status == 404:
ns = k8s_client.V1Namespace(
metadata=k8s_client.V1ObjectMeta(
name=K8S_NAMESPACE,
labels={
"app.kubernetes.io/name": "deer-flow",
"app.kubernetes.io/component": "sandbox",
},
)
)
core_v1.create_namespace(ns)
logger.info(f"Created namespace '{K8S_NAMESPACE}'")
else:
raise
# ── FastAPI lifespan ─────────────────────────────────────────────────────
@asynccontextmanager
async def lifespan(_app: FastAPI):
global core_v1
_wait_for_kubeconfig()
core_v1 = _init_k8s_client()
_ensure_namespace()
logger.info("Provisioner is ready (using host Kubernetes)")
yield
app = FastAPI(title="DeerFlow Sandbox Provisioner", lifespan=lifespan)
# ── Request / Response models ───────────────────────────────────────────
class CreateSandboxRequest(BaseModel):
sandbox_id: str
thread_id: str
class SandboxResponse(BaseModel):
sandbox_id: str
sandbox_url: str # Direct access URL, e.g. http://host.docker.internal:{NodePort}
status: str
# ── K8s resource helpers ─────────────────────────────────────────────────
def _pod_name(sandbox_id: str) -> str:
return f"sandbox-{sandbox_id}"
def _svc_name(sandbox_id: str) -> str:
return f"sandbox-{sandbox_id}-svc"
def _sandbox_url(node_port: int) -> str:
"""Build the sandbox URL using the configured NODE_HOST."""
return f"http://{NODE_HOST}:{node_port}"
def _build_pod(sandbox_id: str, thread_id: str) -> k8s_client.V1Pod:
"""Construct a Pod manifest for a single sandbox."""
return k8s_client.V1Pod(
metadata=k8s_client.V1ObjectMeta(
name=_pod_name(sandbox_id),
namespace=K8S_NAMESPACE,
labels={
"app": "deer-flow-sandbox",
"sandbox-id": sandbox_id,
"app.kubernetes.io/name": "deer-flow",
"app.kubernetes.io/component": "sandbox",
},
),
spec=k8s_client.V1PodSpec(
containers=[
k8s_client.V1Container(
name="sandbox",
image=SANDBOX_IMAGE,
image_pull_policy="IfNotPresent",
ports=[
k8s_client.V1ContainerPort(
name="http",
container_port=8080,
protocol="TCP",
)
],
readiness_probe=k8s_client.V1Probe(
http_get=k8s_client.V1HTTPGetAction(
path="/v1/sandbox",
port=8080,
),
initial_delay_seconds=5,
period_seconds=5,
timeout_seconds=3,
failure_threshold=3,
),
liveness_probe=k8s_client.V1Probe(
http_get=k8s_client.V1HTTPGetAction(
path="/v1/sandbox",
port=8080,
),
initial_delay_seconds=10,
period_seconds=10,
timeout_seconds=3,
failure_threshold=3,
),
resources=k8s_client.V1ResourceRequirements(
requests={
"cpu": "100m",
"memory": "256Mi",
"ephemeral-storage": "500Mi",
},
limits={
"cpu": "1000m",
"memory": "1Gi",
"ephemeral-storage": "500Mi",
},
),
volume_mounts=[
k8s_client.V1VolumeMount(
name="skills",
mount_path="/mnt/skills",
read_only=True,
),
k8s_client.V1VolumeMount(
name="user-data",
mount_path="/mnt/user-data",
read_only=False,
),
],
security_context=k8s_client.V1SecurityContext(
privileged=False,
allow_privilege_escalation=True,
),
)
],
volumes=[
k8s_client.V1Volume(
name="skills",
host_path=k8s_client.V1HostPathVolumeSource(
path=SKILLS_HOST_PATH,
type="Directory",
),
),
k8s_client.V1Volume(
name="user-data",
host_path=k8s_client.V1HostPathVolumeSource(
path=f"{THREADS_HOST_PATH}/{thread_id}/user-data",
type="DirectoryOrCreate",
),
),
],
restart_policy="Always",
),
)
def _build_service(sandbox_id: str) -> k8s_client.V1Service:
"""Construct a NodePort Service manifest (port auto-allocated by K8s)."""
return k8s_client.V1Service(
metadata=k8s_client.V1ObjectMeta(
name=_svc_name(sandbox_id),
namespace=K8S_NAMESPACE,
labels={
"app": "deer-flow-sandbox",
"sandbox-id": sandbox_id,
"app.kubernetes.io/name": "deer-flow",
"app.kubernetes.io/component": "sandbox",
},
),
spec=k8s_client.V1ServiceSpec(
type="NodePort",
ports=[
k8s_client.V1ServicePort(
name="http",
port=8080,
target_port=8080,
protocol="TCP",
# nodePort omitted → K8s auto-allocates from the range
)
],
selector={
"sandbox-id": sandbox_id,
},
),
)
def _get_node_port(sandbox_id: str) -> int | None:
"""Read the K8s-allocated NodePort from the Service."""
try:
svc = core_v1.read_namespaced_service(_svc_name(sandbox_id), K8S_NAMESPACE)
for port in svc.spec.ports or []:
if port.name == "http":
return port.node_port
except ApiException:
pass
return None
def _get_pod_phase(sandbox_id: str) -> str:
"""Return the Pod phase (Pending / Running / Succeeded / Failed / Unknown)."""
try:
pod = core_v1.read_namespaced_pod(_pod_name(sandbox_id), K8S_NAMESPACE)
return pod.status.phase or "Unknown"
except ApiException:
return "NotFound"
# ── API endpoints ────────────────────────────────────────────────────────
@app.get("/health")
async def health():
"""Provisioner health check."""
return {"status": "ok"}
@app.post("/api/sandboxes", response_model=SandboxResponse)
async def create_sandbox(req: CreateSandboxRequest):
"""Create a sandbox Pod + NodePort Service for *sandbox_id*.
If the sandbox already exists, returns the existing information
(idempotent).
"""
sandbox_id = req.sandbox_id
thread_id = req.thread_id
logger.info(
f"Received request to create sandbox '{sandbox_id}' for thread '{thread_id}'"
)
# ── Fast path: sandbox already exists ────────────────────────────
existing_port = _get_node_port(sandbox_id)
if existing_port:
return SandboxResponse(
sandbox_id=sandbox_id,
sandbox_url=_sandbox_url(existing_port),
status=_get_pod_phase(sandbox_id),
)
# ── Create Pod ───────────────────────────────────────────────────
try:
core_v1.create_namespaced_pod(K8S_NAMESPACE, _build_pod(sandbox_id, thread_id))
logger.info(f"Created Pod {_pod_name(sandbox_id)}")
except ApiException as exc:
if exc.status != 409: # 409 = AlreadyExists
raise HTTPException(
status_code=500, detail=f"Pod creation failed: {exc.reason}"
)
# ── Create Service ───────────────────────────────────────────────
try:
core_v1.create_namespaced_service(K8S_NAMESPACE, _build_service(sandbox_id))
logger.info(f"Created Service {_svc_name(sandbox_id)}")
except ApiException as exc:
if exc.status != 409:
# Roll back the Pod on failure
try:
core_v1.delete_namespaced_pod(_pod_name(sandbox_id), K8S_NAMESPACE)
except ApiException:
pass
raise HTTPException(
status_code=500, detail=f"Service creation failed: {exc.reason}"
)
# ── Read the auto-allocated NodePort ─────────────────────────────
node_port: int | None = None
for _ in range(20):
node_port = _get_node_port(sandbox_id)
if node_port:
break
time.sleep(0.5)
if not node_port:
raise HTTPException(
status_code=500, detail="NodePort was not allocated in time"
)
return SandboxResponse(
sandbox_id=sandbox_id,
sandbox_url=_sandbox_url(node_port),
status=_get_pod_phase(sandbox_id),
)
@app.delete("/api/sandboxes/{sandbox_id}")
async def destroy_sandbox(sandbox_id: str):
"""Destroy a sandbox Pod + Service."""
errors: list[str] = []
# Delete Service
try:
core_v1.delete_namespaced_service(_svc_name(sandbox_id), K8S_NAMESPACE)
logger.info(f"Deleted Service {_svc_name(sandbox_id)}")
except ApiException as exc:
if exc.status != 404:
errors.append(f"service: {exc.reason}")
# Delete Pod
try:
core_v1.delete_namespaced_pod(_pod_name(sandbox_id), K8S_NAMESPACE)
logger.info(f"Deleted Pod {_pod_name(sandbox_id)}")
except ApiException as exc:
if exc.status != 404:
errors.append(f"pod: {exc.reason}")
if errors:
raise HTTPException(
status_code=500, detail=f"Partial cleanup: {', '.join(errors)}"
)
return {"ok": True, "sandbox_id": sandbox_id}
@app.get("/api/sandboxes/{sandbox_id}", response_model=SandboxResponse)
async def get_sandbox(sandbox_id: str):
"""Return current status and URL for a sandbox."""
node_port = _get_node_port(sandbox_id)
if not node_port:
raise HTTPException(status_code=404, detail=f"Sandbox '{sandbox_id}' not found")
return SandboxResponse(
sandbox_id=sandbox_id,
sandbox_url=_sandbox_url(node_port),
status=_get_pod_phase(sandbox_id),
)
@app.get("/api/sandboxes")
async def list_sandboxes():
"""List every sandbox currently managed in the namespace."""
try:
services = core_v1.list_namespaced_service(
K8S_NAMESPACE,
label_selector="app=deer-flow-sandbox",
)
except ApiException as exc:
raise HTTPException(
status_code=500, detail=f"Failed to list services: {exc.reason}"
)
sandboxes: list[SandboxResponse] = []
for svc in services.items:
sid = (svc.metadata.labels or {}).get("sandbox-id")
if not sid:
continue
node_port = None
for port in svc.spec.ports or []:
if port.name == "http":
node_port = port.node_port
break
if node_port:
sandboxes.append(
SandboxResponse(
sandbox_id=sid,
sandbox_url=_sandbox_url(node_port),
status=_get_pod_phase(sid),
)
)
return {"sandboxes": sandboxes, "count": len(sandboxes)}
| {
"repo_id": "bytedance/deer-flow",
"file_path": "docker/provisioner/app.py",
"license": "MIT License",
"lines": 436,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/data-analysis/scripts/analyze.py | """
Data Analysis Script using DuckDB.
Analyzes Excel (.xlsx/.xls) and CSV files using DuckDB's in-process SQL engine.
Supports schema inspection, SQL queries, statistical summaries, and result export.
"""
import argparse
import hashlib
import json
import logging
import os
import re
import sys
import tempfile
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
try:
import duckdb
except ImportError:
logger.error("duckdb is not installed. Installing...")
os.system(f"{sys.executable} -m pip install duckdb openpyxl -q")
import duckdb
try:
import openpyxl # noqa: F401
except ImportError:
os.system(f"{sys.executable} -m pip install openpyxl -q")
# Cache directory for persistent DuckDB databases
CACHE_DIR = os.path.join(tempfile.gettempdir(), ".data-analysis-cache")
TABLE_MAP_SUFFIX = ".table_map.json"
def compute_files_hash(files: list[str]) -> str:
"""Compute a combined SHA256 hash of all input files for cache key."""
hasher = hashlib.sha256()
for file_path in sorted(files):
try:
with open(file_path, "rb") as f:
while chunk := f.read(8192):
hasher.update(chunk)
except OSError:
# Include path as fallback if file can't be read
hasher.update(file_path.encode())
return hasher.hexdigest()
def get_cache_db_path(files_hash: str) -> str:
"""Get the path to the cached DuckDB database file."""
os.makedirs(CACHE_DIR, exist_ok=True)
return os.path.join(CACHE_DIR, f"{files_hash}.duckdb")
def get_table_map_path(files_hash: str) -> str:
"""Get the path to the cached table map JSON file."""
return os.path.join(CACHE_DIR, f"{files_hash}{TABLE_MAP_SUFFIX}")
def save_table_map(files_hash: str, table_map: dict[str, str]) -> None:
"""Save table map to a JSON file alongside the cached DB."""
path = get_table_map_path(files_hash)
with open(path, "w", encoding="utf-8") as f:
json.dump(table_map, f, ensure_ascii=False)
def load_table_map(files_hash: str) -> dict[str, str] | None:
"""Load table map from cache. Returns None if not found."""
path = get_table_map_path(files_hash)
if not os.path.exists(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def sanitize_table_name(name: str) -> str:
"""Sanitize a sheet/file name into a valid SQL table name."""
sanitized = re.sub(r"[^\w]", "_", name)
if sanitized and sanitized[0].isdigit():
sanitized = f"t_{sanitized}"
return sanitized
def load_files(con: duckdb.DuckDBPyConnection, files: list[str]) -> dict[str, str]:
"""
Load Excel/CSV files into DuckDB tables.
Returns a mapping of original_name -> sanitized_table_name.
"""
con.execute("INSTALL spatial; LOAD spatial;")
table_map: dict[str, str] = {}
for file_path in files:
if not os.path.exists(file_path):
logger.error(f"File not found: {file_path}")
continue
ext = os.path.splitext(file_path)[1].lower()
if ext in (".xlsx", ".xls"):
_load_excel(con, file_path, table_map)
elif ext == ".csv":
_load_csv(con, file_path, table_map)
else:
logger.warning(f"Unsupported file format: {ext} ({file_path})")
return table_map
def _load_excel(
con: duckdb.DuckDBPyConnection, file_path: str, table_map: dict[str, str]
) -> None:
"""Load all sheets from an Excel file into DuckDB tables."""
import openpyxl
wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
sheet_names = wb.sheetnames
wb.close()
for sheet_name in sheet_names:
table_name = sanitize_table_name(sheet_name)
# Handle duplicate table names
original_table_name = table_name
counter = 1
while table_name in table_map.values():
table_name = f"{original_table_name}_{counter}"
counter += 1
try:
con.execute(
f"""
CREATE TABLE "{table_name}" AS
SELECT * FROM st_read(
'{file_path}',
layer = '{sheet_name}',
open_options = ['HEADERS=FORCE', 'FIELD_TYPES=AUTO']
)
"""
)
table_map[sheet_name] = table_name
row_count = con.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[
0
]
logger.info(
f" Loaded sheet '{sheet_name}' -> table '{table_name}' ({row_count} rows)"
)
except Exception as e:
logger.warning(f" Failed to load sheet '{sheet_name}': {e}")
def _load_csv(
con: duckdb.DuckDBPyConnection, file_path: str, table_map: dict[str, str]
) -> None:
"""Load a CSV file into a DuckDB table."""
base_name = os.path.splitext(os.path.basename(file_path))[0]
table_name = sanitize_table_name(base_name)
# Handle duplicate table names
original_table_name = table_name
counter = 1
while table_name in table_map.values():
table_name = f"{original_table_name}_{counter}"
counter += 1
try:
con.execute(
f"""
CREATE TABLE "{table_name}" AS
SELECT * FROM read_csv_auto('{file_path}')
"""
)
table_map[base_name] = table_name
row_count = con.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
logger.info(
f" Loaded CSV '{base_name}' -> table '{table_name}' ({row_count} rows)"
)
except Exception as e:
logger.warning(f" Failed to load CSV '{base_name}': {e}")
def action_inspect(con: duckdb.DuckDBPyConnection, table_map: dict[str, str]) -> str:
"""Inspect the schema of all loaded tables."""
output_parts = []
for original_name, table_name in table_map.items():
output_parts.append(f"\n{'=' * 60}")
output_parts.append(f'Table: {original_name} (SQL name: "{table_name}")')
output_parts.append(f"{'=' * 60}")
# Get row count
row_count = con.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
output_parts.append(f"Rows: {row_count}")
# Get column info
columns = con.execute(f'DESCRIBE "{table_name}"').fetchall()
output_parts.append(f"\nColumns ({len(columns)}):")
output_parts.append(f"{'Name':<30} {'Type':<15} {'Nullable'}")
output_parts.append(f"{'-' * 30} {'-' * 15} {'-' * 8}")
for col in columns:
col_name, col_type, nullable = col[0], col[1], col[2]
output_parts.append(f"{col_name:<30} {col_type:<15} {nullable}")
# Get non-null counts per column
col_names = [col[0] for col in columns]
non_null_parts = []
for c in col_names:
non_null_parts.append(f'COUNT("{c}") as "{c}"')
non_null_sql = f'SELECT {", ".join(non_null_parts)} FROM "{table_name}"'
try:
non_null_counts = con.execute(non_null_sql).fetchone()
output_parts.append(f"\nNon-null counts:")
for i, c in enumerate(col_names):
output_parts.append(f" {c}: {non_null_counts[i]} / {row_count}")
except Exception:
pass
# Sample data (first 5 rows)
output_parts.append(f"\nSample data (first 5 rows):")
try:
sample = con.execute(f'SELECT * FROM "{table_name}" LIMIT 5').fetchdf()
output_parts.append(sample.to_string(index=False))
except Exception:
sample = con.execute(f'SELECT * FROM "{table_name}" LIMIT 5').fetchall()
header = [col[0] for col in columns]
output_parts.append(" " + " | ".join(header))
for row in sample:
output_parts.append(" " + " | ".join(str(v) for v in row))
result = "\n".join(output_parts)
print(result)
return result
def action_query(
con: duckdb.DuckDBPyConnection,
sql: str,
table_map: dict[str, str],
output_file: str | None = None,
) -> str:
"""Execute a SQL query and return/export results."""
# Replace original sheet/file names with sanitized table names in SQL
modified_sql = sql
for original_name, table_name in sorted(
table_map.items(), key=lambda x: len(x[0]), reverse=True
):
if original_name != table_name:
# Replace occurrences not already quoted
modified_sql = re.sub(
rf"\b{re.escape(original_name)}\b",
f'"{table_name}"',
modified_sql,
)
try:
result = con.execute(modified_sql)
columns = [desc[0] for desc in result.description]
rows = result.fetchall()
except Exception as e:
error_msg = f"SQL Error: {e}\n\nAvailable tables:\n"
for orig, tbl in table_map.items():
cols = con.execute(f'DESCRIBE "{tbl}"').fetchall()
col_names = [c[0] for c in cols]
error_msg += f' "{tbl}" ({orig}): {", ".join(col_names)}\n'
print(error_msg)
return error_msg
# Format output
if output_file:
return _export_results(columns, rows, output_file)
# Print as table
return _format_table(columns, rows)
def _format_table(columns: list[str], rows: list[tuple]) -> str:
"""Format query results as a readable table."""
if not rows:
msg = "Query returned 0 rows."
print(msg)
return msg
# Calculate column widths
col_widths = [len(str(c)) for c in columns]
for row in rows:
for i, val in enumerate(row):
col_widths[i] = max(col_widths[i], len(str(val)))
# Cap column width
max_width = 40
col_widths = [min(w, max_width) for w in col_widths]
# Build table
parts = []
header = " | ".join(str(c).ljust(col_widths[i]) for i, c in enumerate(columns))
separator = "-+-".join("-" * col_widths[i] for i in range(len(columns)))
parts.append(header)
parts.append(separator)
for row in rows:
row_str = " | ".join(
str(v)[:max_width].ljust(col_widths[i]) for i, v in enumerate(row)
)
parts.append(row_str)
parts.append(f"\n({len(rows)} rows)")
result = "\n".join(parts)
print(result)
return result
def _export_results(columns: list[str], rows: list[tuple], output_file: str) -> str:
"""Export query results to a file (CSV, JSON, or Markdown)."""
os.makedirs(os.path.dirname(output_file), exist_ok=True)
ext = os.path.splitext(output_file)[1].lower()
if ext == ".csv":
import csv
with open(output_file, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(columns)
writer.writerows(rows)
elif ext == ".json":
records = []
for row in rows:
record = {}
for i, col in enumerate(columns):
val = row[i]
# Handle non-JSON-serializable types
if hasattr(val, "isoformat"):
val = val.isoformat()
elif isinstance(val, (bytes, bytearray)):
val = val.hex()
record[col] = val
records.append(record)
with open(output_file, "w", encoding="utf-8") as f:
json.dump(records, f, indent=2, ensure_ascii=False, default=str)
elif ext == ".md":
with open(output_file, "w", encoding="utf-8") as f:
# Header
f.write("| " + " | ".join(columns) + " |\n")
f.write("| " + " | ".join("---" for _ in columns) + " |\n")
# Rows
for row in rows:
f.write(
"| " + " | ".join(str(v).replace("|", "\\|") for v in row) + " |\n"
)
else:
msg = f"Unsupported output format: {ext}. Use .csv, .json, or .md"
print(msg)
return msg
msg = f"Results exported to {output_file} ({len(rows)} rows)"
print(msg)
return msg
def action_summary(
con: duckdb.DuckDBPyConnection,
table_name: str,
table_map: dict[str, str],
) -> str:
"""Generate statistical summary for a table."""
# Resolve table name
resolved = table_map.get(table_name, table_name)
try:
columns = con.execute(f'DESCRIBE "{resolved}"').fetchall()
except Exception:
available = ", ".join(f'"{t}" ({o})' for o, t in table_map.items())
msg = f"Table '{table_name}' not found. Available tables: {available}"
print(msg)
return msg
row_count = con.execute(f'SELECT COUNT(*) FROM "{resolved}"').fetchone()[0]
output_parts = []
output_parts.append(f"\nStatistical Summary: {table_name}")
output_parts.append(f"Total rows: {row_count}")
output_parts.append(f"{'=' * 70}")
numeric_types = {
"BIGINT",
"INTEGER",
"SMALLINT",
"TINYINT",
"DOUBLE",
"FLOAT",
"DECIMAL",
"HUGEINT",
"REAL",
"NUMERIC",
}
for col in columns:
col_name, col_type = col[0], col[1].upper()
output_parts.append(f"\n--- {col_name} ({col[1]}) ---")
# Check base type (strip parameterized parts)
base_type = re.sub(r"\(.*\)", "", col_type).strip()
if base_type in numeric_types:
try:
stats = con.execute(f"""
SELECT
COUNT("{col_name}") as count,
AVG("{col_name}")::DOUBLE as mean,
STDDEV("{col_name}")::DOUBLE as std,
MIN("{col_name}") as min,
QUANTILE_CONT("{col_name}", 0.25) as q25,
MEDIAN("{col_name}") as median,
QUANTILE_CONT("{col_name}", 0.75) as q75,
MAX("{col_name}") as max,
COUNT(*) - COUNT("{col_name}") as null_count
FROM "{resolved}"
""").fetchone()
labels = [
"count",
"mean",
"std",
"min",
"25%",
"50%",
"75%",
"max",
"nulls",
]
for label, val in zip(labels, stats):
if isinstance(val, float):
output_parts.append(f" {label:<8}: {val:,.4f}")
else:
output_parts.append(f" {label:<8}: {val}")
except Exception as e:
output_parts.append(f" Error computing stats: {e}")
else:
try:
stats = con.execute(f"""
SELECT
COUNT("{col_name}") as count,
COUNT(DISTINCT "{col_name}") as unique_count,
MODE("{col_name}") as mode_val,
COUNT(*) - COUNT("{col_name}") as null_count
FROM "{resolved}"
""").fetchone()
output_parts.append(f" count : {stats[0]}")
output_parts.append(f" unique : {stats[1]}")
output_parts.append(f" top : {stats[2]}")
output_parts.append(f" nulls : {stats[3]}")
# Show top 5 values
top_vals = con.execute(f"""
SELECT "{col_name}", COUNT(*) as freq
FROM "{resolved}"
WHERE "{col_name}" IS NOT NULL
GROUP BY "{col_name}"
ORDER BY freq DESC
LIMIT 5
""").fetchall()
if top_vals:
output_parts.append(f" top values:")
for val, freq in top_vals:
pct = (freq / row_count * 100) if row_count > 0 else 0
output_parts.append(f" {val}: {freq} ({pct:.1f}%)")
except Exception as e:
output_parts.append(f" Error computing stats: {e}")
result = "\n".join(output_parts)
print(result)
return result
def main():
parser = argparse.ArgumentParser(description="Analyze Excel/CSV files using DuckDB")
parser.add_argument(
"--files",
nargs="+",
required=True,
help="Paths to Excel (.xlsx/.xls) or CSV files",
)
parser.add_argument(
"--action",
required=True,
choices=["inspect", "query", "summary"],
help="Action to perform: inspect, query, or summary",
)
parser.add_argument(
"--sql",
type=str,
default=None,
help="SQL query to execute (required for 'query' action)",
)
parser.add_argument(
"--table",
type=str,
default=None,
help="Table name for summary (required for 'summary' action)",
)
parser.add_argument(
"--output-file",
type=str,
default=None,
help="Path to export results (CSV/JSON/MD)",
)
args = parser.parse_args()
# Validate arguments
if args.action == "query" and not args.sql:
parser.error("--sql is required for 'query' action")
if args.action == "summary" and not args.table:
parser.error("--table is required for 'summary' action")
# Compute file hash for caching
files_hash = compute_files_hash(args.files)
db_path = get_cache_db_path(files_hash)
cached_table_map = load_table_map(files_hash)
if cached_table_map and os.path.exists(db_path):
# Cache hit: connect to existing DB
logger.info(f"Cache hit! Using cached database: {db_path}")
con = duckdb.connect(db_path, read_only=True)
table_map = cached_table_map
logger.info(
f"Loaded {len(table_map)} table(s) from cache: {', '.join(table_map.keys())}"
)
else:
# Cache miss: load files and persist to DB
logger.info("Loading files (first time, will cache for future use)...")
con = duckdb.connect(db_path)
table_map = load_files(con, args.files)
if not table_map:
logger.error("No tables were loaded. Check file paths and formats.")
# Clean up empty DB file
con.close()
if os.path.exists(db_path):
os.remove(db_path)
sys.exit(1)
# Save table map for future cache lookups
save_table_map(files_hash, table_map)
logger.info(
f"\nLoaded {len(table_map)} table(s): {', '.join(table_map.keys())}"
)
logger.info(f"Cached database saved to: {db_path}")
# Perform action
if args.action == "inspect":
action_inspect(con, table_map)
elif args.action == "query":
action_query(con, args.sql, table_map, args.output_file)
elif args.action == "summary":
action_summary(con, args.table, table_map)
con.close()
if __name__ == "__main__":
main()
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/data-analysis/scripts/analyze.py",
"license": "MIT License",
"lines": 482,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/github-deep-research/scripts/github_api.py | #!/usr/bin/env python3
"""
GitHub API client for deep research.
Uses requests for HTTP operations.
"""
import json
import sys
from typing import Any, Dict, List, Optional
try:
import requests
except ImportError:
# Fallback to urllib if requests not available
import urllib.error
import urllib.request
class RequestsFallback:
"""Minimal requests-like interface using urllib."""
class Response:
def __init__(self, data: bytes, status: int):
self._data = data
self.status_code = status
self.text = data.decode("utf-8", errors="replace")
def json(self):
return json.loads(self._data)
def raise_for_status(self):
if self.status_code >= 400:
raise Exception(f"HTTP {self.status_code}")
@staticmethod
def get(url: str, headers: dict = None, params: dict = None, timeout: int = 30):
if params:
query = "&".join(f"{k}={v}" for k, v in params.items())
url = f"{url}?{query}"
req = urllib.request.Request(url, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return RequestsFallback.Response(resp.read(), resp.status)
except urllib.error.HTTPError as e:
return RequestsFallback.Response(e.read(), e.code)
requests = RequestsFallback()
class GitHubAPI:
"""GitHub API client for repository analysis."""
BASE_URL = "https://api.github.com"
def __init__(self, token: Optional[str] = None):
"""
Initialize GitHub API client.
Args:
token: Optional GitHub personal access token for higher rate limits
"""
self.token = token
self.headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Deep-Research-Bot/1.0",
}
if token:
self.headers["Authorization"] = f"token {token}"
def _get(
self, endpoint: str, params: Optional[Dict] = None, accept: Optional[str] = None
) -> Any:
"""Make GET request to GitHub API."""
url = f"{self.BASE_URL}{endpoint}"
headers = self.headers.copy()
if accept:
headers["Accept"] = accept
resp = requests.get(url, headers=headers, params=params, timeout=30)
resp.raise_for_status()
if "application/vnd.github.raw" in (accept or ""):
return resp.text
return resp.json()
def get_repo_info(self, owner: str, repo: str) -> Dict:
"""Get basic repository information."""
return self._get(f"/repos/{owner}/{repo}")
def get_readme(self, owner: str, repo: str) -> str:
"""Get repository README content as markdown."""
try:
return self._get(
f"/repos/{owner}/{repo}/readme", accept="application/vnd.github.raw"
)
except Exception as e:
return f"[README not found: {e}]"
def get_tree(
self, owner: str, repo: str, branch: str = "main", recursive: bool = True
) -> Dict:
"""Get repository directory tree."""
params = {"recursive": "1"} if recursive else {}
try:
return self._get(f"/repos/{owner}/{repo}/git/trees/{branch}", params)
except Exception:
# Try 'master' if 'main' fails
if branch == "main":
return self._get(f"/repos/{owner}/{repo}/git/trees/master", params)
raise
def get_file_content(self, owner: str, repo: str, path: str) -> str:
"""Get content of a specific file."""
try:
return self._get(
f"/repos/{owner}/{repo}/contents/{path}",
accept="application/vnd.github.raw",
)
except Exception as e:
return f"[File not found: {e}]"
def get_languages(self, owner: str, repo: str) -> Dict[str, int]:
"""Get repository languages and their bytes."""
return self._get(f"/repos/{owner}/{repo}/languages")
def get_contributors(self, owner: str, repo: str, limit: int = 30) -> List[Dict]:
"""Get repository contributors."""
return self._get(
f"/repos/{owner}/{repo}/contributors", params={"per_page": min(limit, 100)}
)
def get_recent_commits(
self, owner: str, repo: str, limit: int = 50, since: Optional[str] = None
) -> List[Dict]:
"""
Get recent commits.
Args:
owner: Repository owner
repo: Repository name
limit: Max commits to fetch
since: ISO date string to fetch commits since
"""
params = {"per_page": min(limit, 100)}
if since:
params["since"] = since
return self._get(f"/repos/{owner}/{repo}/commits", params)
def get_issues(
self,
owner: str,
repo: str,
state: str = "all",
limit: int = 30,
labels: Optional[str] = None,
) -> List[Dict]:
"""
Get repository issues.
Args:
state: 'open', 'closed', or 'all'
labels: Comma-separated label names
"""
params = {"state": state, "per_page": min(limit, 100)}
if labels:
params["labels"] = labels
return self._get(f"/repos/{owner}/{repo}/issues", params)
def get_pull_requests(
self, owner: str, repo: str, state: str = "all", limit: int = 30
) -> List[Dict]:
"""Get repository pull requests."""
return self._get(
f"/repos/{owner}/{repo}/pulls",
params={"state": state, "per_page": min(limit, 100)},
)
def get_releases(self, owner: str, repo: str, limit: int = 10) -> List[Dict]:
"""Get repository releases."""
return self._get(
f"/repos/{owner}/{repo}/releases", params={"per_page": min(limit, 100)}
)
def get_tags(self, owner: str, repo: str, limit: int = 20) -> List[Dict]:
"""Get repository tags."""
return self._get(
f"/repos/{owner}/{repo}/tags", params={"per_page": min(limit, 100)}
)
def search_issues(self, owner: str, repo: str, query: str, limit: int = 30) -> Dict:
"""Search issues and PRs in repository."""
q = f"repo:{owner}/{repo} {query}"
return self._get("/search/issues", params={"q": q, "per_page": min(limit, 100)})
def get_commit_activity(self, owner: str, repo: str) -> List[Dict]:
"""Get weekly commit activity for the last year."""
return self._get(f"/repos/{owner}/{repo}/stats/commit_activity")
def get_code_frequency(self, owner: str, repo: str) -> List[List[int]]:
"""Get weekly additions/deletions."""
return self._get(f"/repos/{owner}/{repo}/stats/code_frequency")
def format_tree(self, tree_data: Dict, max_depth: int = 3) -> str:
"""
Format tree data as text directory structure.
Args:
tree_data: Response from get_tree()
max_depth: Maximum depth to display
"""
if "tree" not in tree_data:
return "[Unable to parse tree]"
lines = []
for item in tree_data["tree"]:
path = item["path"]
depth = path.count("/")
if depth < max_depth:
indent = " " * depth
name = path.split("/")[-1]
if item["type"] == "tree":
lines.append(f"{indent}{name}/")
else:
lines.append(f"{indent}{name}")
return "\n".join(lines[:100]) # Limit output
def summarize_repo(self, owner: str, repo: str) -> Dict:
"""
Get comprehensive repository summary.
Returns dict with: info, languages, contributor_count,
recent_activity, top_issues, latest_release
"""
info = self.get_repo_info(owner, repo)
summary = {
"name": info.get("full_name"),
"description": info.get("description"),
"url": info.get("html_url"),
"stars": info.get("stargazers_count"),
"forks": info.get("forks_count"),
"open_issues": info.get("open_issues_count"),
"language": info.get("language"),
"license": info.get("license", {}).get("spdx_id")
if info.get("license")
else None,
"created_at": info.get("created_at"),
"updated_at": info.get("updated_at"),
"pushed_at": info.get("pushed_at"),
"default_branch": info.get("default_branch"),
"topics": info.get("topics", []),
}
# Add languages
try:
summary["languages"] = self.get_languages(owner, repo)
except Exception:
summary["languages"] = {}
# Add contributor count
try:
contributors = self.get_contributors(owner, repo, limit=1)
# GitHub returns Link header with total, but we approximate
summary["contributor_count"] = len(
self.get_contributors(owner, repo, limit=100)
)
except Exception:
summary["contributor_count"] = "N/A"
# Latest release
try:
releases = self.get_releases(owner, repo, limit=1)
if releases:
summary["latest_release"] = {
"tag": releases[0].get("tag_name"),
"name": releases[0].get("name"),
"date": releases[0].get("published_at"),
}
except Exception:
summary["latest_release"] = None
return summary
def main():
"""CLI interface for testing."""
if len(sys.argv) < 3:
print("Usage: python github_api.py <owner> <repo> [command]")
print("Commands: info, readme, tree, languages, contributors,")
print(" commits, issues, prs, releases, summary")
sys.exit(1)
owner, repo = sys.argv[1], sys.argv[2]
command = sys.argv[3] if len(sys.argv) > 3 else "summary"
api = GitHubAPI()
commands = {
"info": lambda: api.get_repo_info(owner, repo),
"readme": lambda: api.get_readme(owner, repo),
"tree": lambda: api.format_tree(api.get_tree(owner, repo)),
"languages": lambda: api.get_languages(owner, repo),
"contributors": lambda: api.get_contributors(owner, repo),
"commits": lambda: api.get_recent_commits(owner, repo),
"issues": lambda: api.get_issues(owner, repo),
"prs": lambda: api.get_pull_requests(owner, repo),
"releases": lambda: api.get_releases(owner, repo),
"summary": lambda: api.summarize_repo(owner, repo),
}
if command not in commands:
print(f"Unknown command: {command}")
sys.exit(1)
try:
result = commands[command]()
if isinstance(result, str):
print(result)
else:
print(json.dumps(result, indent=2, default=str))
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/github-deep-research/scripts/github_api.py",
"license": "MIT License",
"lines": 275,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/image-generation/scripts/generate.py | import base64
import os
import requests
from PIL import Image
def validate_image(image_path: str) -> bool:
"""
Validate if an image file can be opened and is not corrupted.
Args:
image_path: Path to the image file
Returns:
True if the image is valid and can be opened, False otherwise
"""
try:
with Image.open(image_path) as img:
img.verify() # Verify that it's a valid image
# Re-open to check if it can be fully loaded (verify() may not catch all issues)
with Image.open(image_path) as img:
img.load() # Force load the image data
return True
except Exception as e:
print(f"Warning: Image '{image_path}' is invalid or corrupted: {e}")
return False
def generate_image(
prompt_file: str,
reference_images: list[str],
output_file: str,
aspect_ratio: str = "16:9",
) -> str:
with open(prompt_file, "r") as f:
prompt = f.read()
parts = []
i = 0
# Filter out invalid reference images
valid_reference_images = []
for ref_img in reference_images:
if validate_image(ref_img):
valid_reference_images.append(ref_img)
else:
print(f"Skipping invalid reference image: {ref_img}")
if len(valid_reference_images) < len(reference_images):
print(f"Note: {len(reference_images) - len(valid_reference_images)} reference image(s) were skipped due to validation failure.")
for reference_image in valid_reference_images:
i += 1
with open(reference_image, "rb") as f:
image_b64 = base64.b64encode(f.read()).decode("utf-8")
parts.append(
{
"inlineData": {
"mimeType": "image/jpeg",
"data": image_b64,
}
}
)
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return "GEMINI_API_KEY is not set"
response = requests.post(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent",
headers={
"x-goog-api-key": api_key,
"Content-Type": "application/json",
},
json={
"generationConfig": {"imageConfig": {"aspectRatio": aspect_ratio}},
"contents": [{"parts": [*parts, {"text": prompt}]}],
},
)
response.raise_for_status()
json = response.json()
parts: list[dict] = json["candidates"][0]["content"]["parts"]
image_parts = [part for part in parts if part.get("inlineData", False)]
if len(image_parts) == 1:
base64_image = image_parts[0]["inlineData"]["data"]
# Save the image to a file
with open(output_file, "wb") as f:
f.write(base64.b64decode(base64_image))
return f"Successfully generated image to {output_file}"
else:
raise Exception("Failed to generate image")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate images using Gemini API")
parser.add_argument(
"--prompt-file",
required=True,
help="Absolute path to JSON prompt file",
)
parser.add_argument(
"--reference-images",
nargs="*",
default=[],
help="Absolute paths to reference images (space-separated)",
)
parser.add_argument(
"--output-file",
required=True,
help="Output path for generated image",
)
parser.add_argument(
"--aspect-ratio",
required=False,
default="16:9",
help="Aspect ratio of the generated image",
)
args = parser.parse_args()
try:
print(
generate_image(
args.prompt_file,
args.reference_images,
args.output_file,
args.aspect_ratio,
)
)
except Exception as e:
print(f"Error while generating image: {e}")
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/image-generation/scripts/generate.py",
"license": "MIT License",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/podcast-generation/scripts/generate.py | import argparse
import base64
import json
import logging
import os
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Literal, Optional
import requests
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Types
class ScriptLine:
def __init__(self, speaker: Literal["male", "female"] = "male", paragraph: str = ""):
self.speaker = speaker
self.paragraph = paragraph
class Script:
def __init__(self, locale: Literal["en", "zh"] = "en", lines: Optional[list[ScriptLine]] = None):
self.locale = locale
self.lines = lines or []
@classmethod
def from_dict(cls, data: dict) -> "Script":
script = cls(locale=data.get("locale", "en"))
for line in data.get("lines", []):
script.lines.append(
ScriptLine(
speaker=line.get("speaker", "male"),
paragraph=line.get("paragraph", ""),
)
)
return script
def text_to_speech(text: str, voice_type: str) -> Optional[bytes]:
"""Convert text to speech using Volcengine TTS."""
app_id = os.getenv("VOLCENGINE_TTS_APPID")
access_token = os.getenv("VOLCENGINE_TTS_ACCESS_TOKEN")
cluster = os.getenv("VOLCENGINE_TTS_CLUSTER", "volcano_tts")
if not app_id or not access_token:
raise ValueError(
"VOLCENGINE_TTS_APPID and VOLCENGINE_TTS_ACCESS_TOKEN environment variables must be set"
)
url = "https://openspeech.bytedance.com/api/v1/tts"
# Authentication: Bearer token with semicolon separator
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer;{access_token}",
}
payload = {
"app": {
"appid": app_id,
"token": "access_token", # literal string, not the actual token
"cluster": cluster,
},
"user": {"uid": "podcast-generator"},
"audio": {
"voice_type": voice_type,
"encoding": "mp3",
"speed_ratio": 1.2,
},
"request": {
"reqid": str(uuid.uuid4()), # must be unique UUID
"text": text,
"text_type": "plain",
"operation": "query",
},
}
try:
response = requests.post(url, json=payload, headers=headers)
if response.status_code != 200:
logger.error(f"TTS API error: {response.status_code} - {response.text}")
return None
result = response.json()
if result.get("code") != 3000:
logger.error(f"TTS error: {result.get('message')} (code: {result.get('code')})")
return None
audio_data = result.get("data")
if audio_data:
return base64.b64decode(audio_data)
except Exception as e:
logger.error(f"TTS error: {str(e)}")
return None
def _process_line(args: tuple[int, ScriptLine, int]) -> tuple[int, Optional[bytes]]:
"""Process a single script line for TTS. Returns (index, audio_bytes)."""
i, line, total = args
# Select voice based on speaker gender
if line.speaker == "male":
voice_type = "zh_male_yangguangqingnian_moon_bigtts" # Male voice
else:
voice_type = "zh_female_sajiaonvyou_moon_bigtts" # Female voice
logger.info(f"Processing line {i + 1}/{total} ({line.speaker})")
audio = text_to_speech(line.paragraph, voice_type)
if not audio:
logger.warning(f"Failed to generate audio for line {i + 1}")
return (i, audio)
def tts_node(script: Script, max_workers: int = 4) -> list[bytes]:
"""Convert script lines to audio chunks using TTS with multi-threading."""
logger.info(f"Converting script to audio using {max_workers} workers...")
total = len(script.lines)
tasks = [(i, line, total) for i, line in enumerate(script.lines)]
# Use ThreadPoolExecutor for parallel TTS generation
results: dict[int, Optional[bytes]] = {}
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(_process_line, task): task[0] for task in tasks}
for future in as_completed(futures):
idx, audio = future.result()
results[idx] = audio
# Collect results in order, skipping failed ones
audio_chunks = []
for i in range(total):
audio = results.get(i)
if audio:
audio_chunks.append(audio)
logger.info(f"Generated {len(audio_chunks)} audio chunks")
return audio_chunks
def mix_audio(audio_chunks: list[bytes]) -> bytes:
"""Combine audio chunks into a single audio file."""
logger.info("Mixing audio chunks...")
output = b"".join(audio_chunks)
logger.info("Audio mixing complete")
return output
def generate_markdown(script: Script, title: str = "Podcast Script") -> str:
"""Generate a markdown script from the podcast script."""
lines = [f"# {title}", ""]
for line in script.lines:
speaker_name = "**Host (Male)**" if line.speaker == "male" else "**Host (Female)**"
lines.append(f"{speaker_name}: {line.paragraph}")
lines.append("")
return "\n".join(lines)
def generate_podcast(
script_file: str,
output_file: str,
transcript_file: Optional[str] = None,
) -> str:
"""Generate a podcast from a script JSON file."""
# Read script JSON
with open(script_file, "r", encoding="utf-8") as f:
script_json = json.load(f)
if "lines" not in script_json:
raise ValueError(f"Invalid script format: missing 'lines' key. Got keys: {list(script_json.keys())}")
script = Script.from_dict(script_json)
logger.info(f"Loaded script with {len(script.lines)} lines")
# Generate transcript markdown if requested
if transcript_file:
title = script_json.get("title", "Podcast Script")
markdown_content = generate_markdown(script, title)
transcript_dir = os.path.dirname(transcript_file)
if transcript_dir:
os.makedirs(transcript_dir, exist_ok=True)
with open(transcript_file, "w", encoding="utf-8") as f:
f.write(markdown_content)
logger.info(f"Generated transcript to {transcript_file}")
# Convert to audio
audio_chunks = tts_node(script)
if not audio_chunks:
raise Exception("Failed to generate any audio")
# Mix audio
output_audio = mix_audio(audio_chunks)
# Save output
output_dir = os.path.dirname(output_file)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
with open(output_file, "wb") as f:
f.write(output_audio)
result = f"Successfully generated podcast to {output_file}"
if transcript_file:
result += f" and transcript to {transcript_file}"
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate podcast from script JSON file")
parser.add_argument(
"--script-file",
required=True,
help="Absolute path to script JSON file",
)
parser.add_argument(
"--output-file",
required=True,
help="Output path for generated podcast MP3",
)
parser.add_argument(
"--transcript-file",
required=False,
help="Output path for transcript markdown file (optional)",
)
args = parser.parse_args()
try:
result = generate_podcast(
args.script_file,
args.output_file,
args.transcript_file,
)
print(result)
except Exception as e:
import traceback
print(f"Error generating podcast: {e}")
traceback.print_exc()
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/podcast-generation/scripts/generate.py",
"license": "MIT License",
"lines": 195,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/ppt-generation/scripts/generate.py | import json
import os
from io import BytesIO
from PIL import Image
from pptx import Presentation
from pptx.util import Inches
def generate_ppt(
plan_file: str,
slide_images: list[str],
output_file: str,
) -> str:
"""
Generate a PowerPoint presentation from slide images.
Args:
plan_file: Path to JSON file containing presentation plan
slide_images: List of paths to slide images in order
output_file: Path to output PPTX file
Returns:
Status message
"""
# Load presentation plan
with open(plan_file, "r") as f:
plan = json.load(f)
# Determine slide dimensions based on aspect ratio
aspect_ratio = plan.get("aspect_ratio", "16:9")
if aspect_ratio == "16:9":
slide_width = Inches(13.333)
slide_height = Inches(7.5)
elif aspect_ratio == "4:3":
slide_width = Inches(10)
slide_height = Inches(7.5)
else:
# Default to 16:9
slide_width = Inches(13.333)
slide_height = Inches(7.5)
# Create presentation with specified dimensions
prs = Presentation()
prs.slide_width = slide_width
prs.slide_height = slide_height
# Get blank layout
blank_layout = prs.slide_layouts[6] # Blank layout
# Add each slide image
slides_info = plan.get("slides", [])
for i, image_path in enumerate(slide_images):
if not os.path.exists(image_path):
return f"Error: Slide image not found: {image_path}"
# Add a blank slide
slide = prs.slides.add_slide(blank_layout)
# Load and process image
with Image.open(image_path) as img:
# Convert to RGB if necessary (for PNG with transparency)
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Calculate dimensions to fill slide while maintaining aspect ratio
img_width, img_height = img.size
img_aspect = img_width / img_height
slide_aspect = slide_width / slide_height
# Convert to EMU for calculations
slide_width_emu = int(slide_width)
slide_height_emu = int(slide_height)
if img_aspect > slide_aspect:
# Image is wider - fit to width
new_width_emu = slide_width_emu
new_height_emu = int(slide_width_emu / img_aspect)
left = Inches(0)
top = Inches((slide_height_emu - new_height_emu) / 914400)
else:
# Image is taller - fit to height
new_height_emu = slide_height_emu
new_width_emu = int(slide_height_emu * img_aspect)
left = Inches((slide_width_emu - new_width_emu) / 914400)
top = Inches(0)
# Save processed image to bytes
img_bytes = BytesIO()
img.save(img_bytes, format="JPEG", quality=95)
img_bytes.seek(0)
# Add image to slide
slide.shapes.add_picture(
img_bytes, left, top, Inches(new_width_emu / 914400), Inches(new_height_emu / 914400)
)
# Add speaker notes if available in plan
if i < len(slides_info):
slide_info = slides_info[i]
notes = []
if slide_info.get("title"):
notes.append(f"Title: {slide_info['title']}")
if slide_info.get("subtitle"):
notes.append(f"Subtitle: {slide_info['subtitle']}")
if slide_info.get("key_points"):
notes.append("Key Points:")
for point in slide_info["key_points"]:
notes.append(f" • {point}")
if notes:
notes_slide = slide.notes_slide
text_frame = notes_slide.notes_text_frame
if text_frame is not None:
text_frame.text = "\n".join(notes)
# Save presentation
prs.save(output_file)
return f"Successfully generated presentation with {len(slide_images)} slides to {output_file}"
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Generate PowerPoint presentation from slide images"
)
parser.add_argument(
"--plan-file",
required=True,
help="Absolute path to JSON presentation plan file",
)
parser.add_argument(
"--slide-images",
nargs="+",
required=True,
help="Absolute paths to slide images in order (space-separated)",
)
parser.add_argument(
"--output-file",
required=True,
help="Output path for generated PPTX file",
)
args = parser.parse_args()
try:
print(
generate_ppt(
args.plan_file,
args.slide_images,
args.output_file,
)
)
except Exception as e:
print(f"Error while generating presentation: {e}")
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/ppt-generation/scripts/generate.py",
"license": "MIT License",
"lines": 132,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/skill-creator/scripts/init_skill.py | #!/usr/bin/env python3
"""
Skill Initializer - Creates a new skill from template
Usage:
init_skill.py <skill-name> --path <path>
Examples:
init_skill.py my-new-skill --path skills/public
init_skill.py my-api-helper --path skills/private
init_skill.py custom-skill --path /custom/location
"""
import sys
from pathlib import Path
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
---
# {skill_title}
## Overview
[TODO: 1-2 sentences explaining what this skill enables]
## Structuring This Skill
[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
**1. Workflow-Based** (best for sequential processes)
- Works well when there are clear step-by-step procedures
- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
**2. Task-Based** (best for tool collections)
- Works well when the skill offers different operations/capabilities
- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
**3. Reference/Guidelines** (best for standards or specifications)
- Works well for brand guidelines, coding standards, or requirements
- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
**4. Capabilities-Based** (best for integrated systems)
- Works well when the skill provides multiple interrelated features
- Example: Product Management with "Core Capabilities" → numbered capability list
- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
Delete this entire "Structuring This Skill" section when done - it's just guidance.]
## [TODO: Replace with the first main section based on chosen structure]
[TODO: Add content here. See examples in existing skills:
- Code samples for technical skills
- Decision trees for complex workflows
- Concrete examples with realistic user requests
- References to scripts/templates/references as needed]
## Resources
This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
### scripts/
Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
**Examples from other skills:**
- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
### references/
Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
**Examples from other skills:**
- Product management: `communication.md`, `context_building.md` - detailed workflow guides
- BigQuery: API reference documentation and query examples
- Finance: Schema documentation, company policies
**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
### assets/
Files not intended to be loaded into context, but rather used within the output Claude produces.
**Examples from other skills:**
- Brand styling: PowerPoint template files (.pptx), logo files
- Frontend builder: HTML/React boilerplate project directories
- Typography: Font files (.ttf, .woff2)
**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
---
**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
"""
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
"""
Example helper script for {skill_name}
This is a placeholder script that can be executed directly.
Replace with actual implementation or delete if not needed.
Example real scripts from other skills:
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
"""
def main():
print("This is an example script for {skill_name}")
# TODO: Add actual script logic here
# This could be data processing, file conversion, API calls, etc.
if __name__ == "__main__":
main()
'''
EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
This is a placeholder for detailed reference documentation.
Replace with actual reference content or delete if not needed.
Example real reference docs from other skills:
- product-management/references/communication.md - Comprehensive guide for status updates
- product-management/references/context_building.md - Deep-dive on gathering context
- bigquery/references/ - API references and query examples
## When Reference Docs Are Useful
Reference docs are ideal for:
- Comprehensive API documentation
- Detailed workflow guides
- Complex multi-step processes
- Information too lengthy for main SKILL.md
- Content that's only needed for specific use cases
## Structure Suggestions
### API Reference Example
- Overview
- Authentication
- Endpoints with examples
- Error codes
- Rate limits
### Workflow Guide Example
- Prerequisites
- Step-by-step instructions
- Common patterns
- Troubleshooting
- Best practices
"""
EXAMPLE_ASSET = """# Example Asset File
This placeholder represents where asset files would be stored.
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
Asset files are NOT intended to be loaded into context, but rather used within
the output Claude produces.
Example asset files from other skills:
- Brand guidelines: logo.png, slides_template.pptx
- Frontend builder: hello-world/ directory with HTML/React boilerplate
- Typography: custom-font.ttf, font-family.woff2
- Data: sample_data.csv, test_dataset.json
## Common Asset Types
- Templates: .pptx, .docx, boilerplate directories
- Images: .png, .jpg, .svg, .gif
- Fonts: .ttf, .otf, .woff, .woff2
- Boilerplate code: Project directories, starter files
- Icons: .ico, .svg
- Data files: .csv, .json, .xml, .yaml
Note: This is a text placeholder. Actual assets can be any file type.
"""
def title_case_skill_name(skill_name):
"""Convert hyphenated skill name to Title Case for display."""
return ' '.join(word.capitalize() for word in skill_name.split('-'))
def init_skill(skill_name, path):
"""
Initialize a new skill directory with template SKILL.md.
Args:
skill_name: Name of the skill
path: Path where the skill directory should be created
Returns:
Path to created skill directory, or None if error
"""
# Determine skill directory path
skill_dir = Path(path).resolve() / skill_name
# Check if directory already exists
if skill_dir.exists():
print(f"❌ Error: Skill directory already exists: {skill_dir}")
return None
# Create skill directory
try:
skill_dir.mkdir(parents=True, exist_ok=False)
print(f"✅ Created skill directory: {skill_dir}")
except Exception as e:
print(f"❌ Error creating directory: {e}")
return None
# Create SKILL.md from template
skill_title = title_case_skill_name(skill_name)
skill_content = SKILL_TEMPLATE.format(
skill_name=skill_name,
skill_title=skill_title
)
skill_md_path = skill_dir / 'SKILL.md'
try:
skill_md_path.write_text(skill_content)
print("✅ Created SKILL.md")
except Exception as e:
print(f"❌ Error creating SKILL.md: {e}")
return None
# Create resource directories with example files
try:
# Create scripts/ directory with example script
scripts_dir = skill_dir / 'scripts'
scripts_dir.mkdir(exist_ok=True)
example_script = scripts_dir / 'example.py'
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
example_script.chmod(0o755)
print("✅ Created scripts/example.py")
# Create references/ directory with example reference doc
references_dir = skill_dir / 'references'
references_dir.mkdir(exist_ok=True)
example_reference = references_dir / 'api_reference.md'
example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
print("✅ Created references/api_reference.md")
# Create assets/ directory with example asset placeholder
assets_dir = skill_dir / 'assets'
assets_dir.mkdir(exist_ok=True)
example_asset = assets_dir / 'example_asset.txt'
example_asset.write_text(EXAMPLE_ASSET)
print("✅ Created assets/example_asset.txt")
except Exception as e:
print(f"❌ Error creating resource directories: {e}")
return None
# Print next steps
print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}")
print("\nNext steps:")
print("1. Edit SKILL.md to complete the TODO items and update the description")
print("2. Customize or delete the example files in scripts/, references/, and assets/")
print("3. Run the validator when ready to check the skill structure")
return skill_dir
def main():
if len(sys.argv) < 4 or sys.argv[2] != '--path':
print("Usage: init_skill.py <skill-name> --path <path>")
print("\nSkill name requirements:")
print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
print(" - Lowercase letters, digits, and hyphens only")
print(" - Max 40 characters")
print(" - Must match directory name exactly")
print("\nExamples:")
print(" init_skill.py my-new-skill --path skills/public")
print(" init_skill.py my-api-helper --path skills/private")
print(" init_skill.py custom-skill --path /custom/location")
sys.exit(1)
skill_name = sys.argv[1]
path = sys.argv[3]
print(f"🚀 Initializing skill: {skill_name}")
print(f" Location: {path}")
print()
result = init_skill(skill_name, path)
if result:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/skill-creator/scripts/init_skill.py",
"license": "MIT License",
"lines": 228,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
bytedance/deer-flow:skills/public/skill-creator/scripts/package_skill.py | #!/usr/bin/env python3
"""
Skill Packager - Creates a distributable .skill file of a skill folder
Usage:
python utils/package_skill.py <path/to/skill-folder> [output-directory]
Example:
python utils/package_skill.py skills/public/my-skill
python utils/package_skill.py skills/public/my-skill ./dist
"""
import sys
import zipfile
from pathlib import Path
from quick_validate import validate_skill
def package_skill(skill_path, output_dir=None):
"""
Package a skill folder into a .skill file.
Args:
skill_path: Path to the skill folder
output_dir: Optional output directory for the .skill file (defaults to current directory)
Returns:
Path to the created .skill file, or None if error
"""
skill_path = Path(skill_path).resolve()
# Validate skill folder exists
if not skill_path.exists():
print(f"❌ Error: Skill folder not found: {skill_path}")
return None
if not skill_path.is_dir():
print(f"❌ Error: Path is not a directory: {skill_path}")
return None
# Validate SKILL.md exists
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
print(f"❌ Error: SKILL.md not found in {skill_path}")
return None
# Run validation before packaging
print("🔍 Validating skill...")
valid, message = validate_skill(skill_path)
if not valid:
print(f"❌ Validation failed: {message}")
print(" Please fix the validation errors before packaging.")
return None
print(f"✅ {message}\n")
# Determine output location
skill_name = skill_path.name
if output_dir:
output_path = Path(output_dir).resolve()
output_path.mkdir(parents=True, exist_ok=True)
else:
output_path = Path.cwd()
skill_filename = output_path / f"{skill_name}.skill"
# Create the .skill file (zip format)
try:
with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Walk through the skill directory
for file_path in skill_path.rglob('*'):
if file_path.is_file():
# Calculate the relative path within the zip
arcname = file_path.relative_to(skill_path.parent)
zipf.write(file_path, arcname)
print(f" Added: {arcname}")
print(f"\n✅ Successfully packaged skill to: {skill_filename}")
return skill_filename
except Exception as e:
print(f"❌ Error creating .skill file: {e}")
return None
def main():
if len(sys.argv) < 2:
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
print("\nExample:")
print(" python utils/package_skill.py skills/public/my-skill")
print(" python utils/package_skill.py skills/public/my-skill ./dist")
sys.exit(1)
skill_path = sys.argv[1]
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
print(f"📦 Packaging skill: {skill_path}")
if output_dir:
print(f" Output directory: {output_dir}")
print()
result = package_skill(skill_path, output_dir)
if result:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/skill-creator/scripts/package_skill.py",
"license": "MIT License",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/skill-creator/scripts/quick_validate.py | #!/usr/bin/env python3
"""
Quick validation script for skills - minimal version
"""
import sys
import os
import re
import yaml
from pathlib import Path
def validate_skill(skill_path):
"""Basic validation of a skill"""
skill_path = Path(skill_path)
# Check SKILL.md exists
skill_md = skill_path / 'SKILL.md'
if not skill_md.exists():
return False, "SKILL.md not found"
# Read and validate frontmatter
content = skill_md.read_text()
if not content.startswith('---'):
return False, "No YAML frontmatter found"
# Extract frontmatter
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
if not match:
return False, "Invalid frontmatter format"
frontmatter_text = match.group(1)
# Parse YAML frontmatter
try:
frontmatter = yaml.safe_load(frontmatter_text)
if not isinstance(frontmatter, dict):
return False, "Frontmatter must be a YAML dictionary"
except yaml.YAMLError as e:
return False, f"Invalid YAML in frontmatter: {e}"
# Define allowed properties
ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata'}
# Check for unexpected properties (excluding nested keys under metadata)
unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
if unexpected_keys:
return False, (
f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
)
# Check required fields
if 'name' not in frontmatter:
return False, "Missing 'name' in frontmatter"
if 'description' not in frontmatter:
return False, "Missing 'description' in frontmatter"
# Extract name for validation
name = frontmatter.get('name', '')
if not isinstance(name, str):
return False, f"Name must be a string, got {type(name).__name__}"
name = name.strip()
if name:
# Check naming convention (hyphen-case: lowercase with hyphens)
if not re.match(r'^[a-z0-9-]+$', name):
return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)"
if name.startswith('-') or name.endswith('-') or '--' in name:
return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
# Check name length (max 64 characters per spec)
if len(name) > 64:
return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
# Extract and validate description
description = frontmatter.get('description', '')
if not isinstance(description, str):
return False, f"Description must be a string, got {type(description).__name__}"
description = description.strip()
if description:
# Check for angle brackets
if '<' in description or '>' in description:
return False, "Description cannot contain angle brackets (< or >)"
# Check description length (max 1024 characters per spec)
if len(description) > 1024:
return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
return True, "Skill is valid!"
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python quick_validate.py <skill_directory>")
sys.exit(1)
valid, message = validate_skill(sys.argv[1])
print(message)
sys.exit(0 if valid else 1) | {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/skill-creator/scripts/quick_validate.py",
"license": "MIT License",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
bytedance/deer-flow:skills/public/video-generation/scripts/generate.py | import base64
import os
import time
import requests
def generate_video(
prompt_file: str,
reference_images: list[str],
output_file: str,
aspect_ratio: str = "16:9",
) -> str:
with open(prompt_file, "r") as f:
prompt = f.read()
referenceImages = []
i = 0
json = {
"instances": [{"prompt": prompt}],
}
for reference_image in reference_images:
i += 1
with open(reference_image, "rb") as f:
image_b64 = base64.b64encode(f.read()).decode("utf-8")
referenceImages.append(
{
"image": {"mimeType": "image/jpeg", "bytesBase64Encoded": image_b64},
"referenceType": "asset",
}
)
if i > 0:
json["instances"][0]["referenceImages"] = referenceImages
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return "GEMINI_API_KEY is not set"
response = requests.post(
"https://generativelanguage.googleapis.com/v1beta/models/veo-3.1-generate-preview:predictLongRunning",
headers={
"x-goog-api-key": api_key,
"Content-Type": "application/json",
},
json=json,
)
json = response.json()
operation_name = json["name"]
while True:
response = requests.get(
f"https://generativelanguage.googleapis.com/v1beta/{operation_name}",
headers={
"x-goog-api-key": api_key,
},
)
json = response.json()
if json.get("done", False):
sample = json["response"]["generateVideoResponse"]["generatedSamples"][0]
url = sample["video"]["uri"]
download(url, output_file)
break
time.sleep(3)
return f"The video has been generated successfully to {output_file}"
def download(url: str, output_file: str):
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return "GEMINI_API_KEY is not set"
response = requests.get(
url,
headers={
"x-goog-api-key": api_key,
},
)
with open(output_file, "wb") as f:
f.write(response.content)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate videos using Gemini API")
parser.add_argument(
"--prompt-file",
required=True,
help="Absolute path to JSON prompt file",
)
parser.add_argument(
"--reference-images",
nargs="*",
default=[],
help="Absolute paths to reference images (space-separated)",
)
parser.add_argument(
"--output-file",
required=True,
help="Output path for generated image",
)
parser.add_argument(
"--aspect-ratio",
required=False,
default="16:9",
help="Aspect ratio of the generated image",
)
args = parser.parse_args()
try:
print(
generate_video(
args.prompt_file,
args.reference_images,
args.output_file,
args.aspect_ratio,
)
)
except Exception as e:
print(f"Error while generating video: {e}")
| {
"repo_id": "bytedance/deer-flow",
"file_path": "skills/public/video-generation/scripts/generate.py",
"license": "MIT License",
"lines": 106,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
ccxt/ccxt:python/ccxt/abstract/alp.py | from ccxt.base.types import Entry
class ImplicitAPI:
public_get_currencies = publicGetCurrencies = Entry('currencies/', 'public', 'GET', {'cost': 1})
public_get_pairs = publicGetPairs = Entry('pairs/', 'public', 'GET', {'cost': 1})
public_get_orderbook_pair_name = publicGetOrderbookPairName = Entry('orderbook/{pair_name}', 'public', 'GET', {'cost': 1})
public_get_exchanges = publicGetExchanges = Entry('exchanges/', 'public', 'GET', {'cost': 1})
public_get_charts_pair_type_chart = publicGetChartsPairTypeChart = Entry('charts/{pair}/{type}/chart/', 'public', 'GET', {'cost': 1})
public_get_ticker = publicGetTicker = Entry('ticker/', 'public', 'GET', {'cost': 1})
private_get_wallets = privateGetWallets = Entry('wallets/', 'private', 'GET', {'cost': 50})
private_get_orders_own = privateGetOrdersOwn = Entry('orders/own/', 'private', 'GET', {'cost': 50})
private_get_order_id = privateGetOrderId = Entry('order/{id}/', 'private', 'GET', {'cost': 50})
private_get_exchanges_own = privateGetExchangesOwn = Entry('exchanges/own/', 'private', 'GET', {'cost': 50})
private_get_deposits = privateGetDeposits = Entry('deposits/', 'private', 'GET', {'cost': 50})
private_get_withdraws = privateGetWithdraws = Entry('withdraws/', 'private', 'GET', {'cost': 50})
private_post_order = privatePostOrder = Entry('order/', 'private', 'POST', {'cost': 50})
private_post_order_cancel = privatePostOrderCancel = Entry('order-cancel/', 'private', 'POST', {'cost': 50})
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/abstract/alp.py",
"license": "MIT License",
"lines": 16,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
ccxt/ccxt:python/ccxt/test/base/language_specific/test_throttler_performance.py | import os
import sys
import asyncio
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(root)
import ccxt.async_support as ccxt # noqa: F402
async def test_throttler_performance_helper(exchange, num_requests):
start_time = exchange.milliseconds()
tasks = []
for i in range(num_requests):
tasks.append(throttle_call(exchange, i, start_time))
await asyncio.gather(*tasks)
end_time = exchange.milliseconds()
total_time = (end_time - start_time)
return total_time
async def throttle_call(exchange, index, start_time):
try:
# Use the throttler directly without making any API calls
await exchange.throttle(1) # cost of 1
mock_result = {
'id': 'mock',
'timestamp': exchange.milliseconds(),
'data': 'mock data',
}
assert mock_result['id'] == 'mock'
return mock_result
except Exception as e:
print(f"Throttle call {index + 1} failed: {e}")
raise e
async def test_throttler():
exchange1 = ccxt.binance({
'enableRateLimit': True,
'rateLimiterAlgorithm': 'rollingWindow',
})
try:
rolling_window_time = await test_throttler_performance_helper(exchange1, 100)
finally:
await exchange1.close()
exchange2 = ccxt.binance({
'enableRateLimit': True,
'rateLimiterAlgorithm': 'leakyBucket',
})
try:
leaky_bucket_time = await test_throttler_performance_helper(exchange2, 20)
finally:
await exchange2.close()
exchange3 = ccxt.binance({
'enableRateLimit': True,
'rollingWindowSize': 0.0,
})
try:
rolling_window_0_time = await test_throttler_performance_helper(exchange3, 20)
finally:
await exchange3.close()
rolling_window_time_string = str(round(rolling_window_time, 2))
leaky_bucket_time_string = str(round(leaky_bucket_time, 2))
rolling_window_0_time_string = str(round(rolling_window_0_time, 2)) # uses leakyBucket
assert rolling_window_time <= 1000, 'Rolling window throttler should happen immediately, but time was: ' + rolling_window_time_string
assert leaky_bucket_time >= 500, 'Leaky bucket throttler should take at least half a second for 20 requests, but time was: ' + leaky_bucket_time_string
assert rolling_window_0_time >= 500, 'With rollingWindowSize === 0, the Leaky bucket throttler should be used and take at least half a second for 20 requests, time was: ' + rolling_window_0_time_string
print('┌───────────────────────────────────────────┬──────────────┬─────────────────┐')
print('│ Algorithm │ Time (ms) │ Expected (ms) │')
print('├───────────────────────────────────────────┼──────────────┼─────────────────┤')
print('│ Rolling Window │ ' + rolling_window_time_string.rjust(11) + ' │ ~3 │')
print('│ Leaky Bucket │ ' + leaky_bucket_time_string.rjust(11) + ' │ ~950 │')
print('│ Leaky Bucket (rollingWindowSize === 0) │ ' + rolling_window_0_time_string.rjust(11) + ' │ ~950 │')
print('└───────────────────────────────────────────┴──────────────┴─────────────────┘')
def test_throttler_performance():
try:
# Check if there's already a running event loop
loop = asyncio.get_running_loop()
# If we get here, there's already a loop running
# Create a task and run it (this will be awaited by the caller)
import concurrent.futures
# Can't use asyncio.run() in a running loop, so we need to run in thread pool
with concurrent.futures.ThreadPoolExecutor() as pool:
future = pool.submit(asyncio.run, test_throttler())
future.result()
except RuntimeError:
# No event loop is running, safe to use asyncio.run()
asyncio.run(test_throttler())
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/test/base/language_specific/test_throttler_performance.py",
"license": "MIT License",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/P2PKH_addr.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for P2PKH address encoding/decoding."""
# Imports
from enum import Enum, auto, unique
from typing import Any, Union
from .addr_dec_utils import AddrDecUtils
from .addr_key_validator import AddrKeyValidator
from .iaddr_decoder import IAddrDecoder
from .iaddr_encoder import IAddrEncoder
from ..base58 import Base58Alphabets, Base58ChecksumError, Base58Decoder, Base58Encoder
from ..bech32 import BchBech32Decoder, BchBech32Encoder, Bech32ChecksumError
from ..ecc import IPublicKey
from ..utils.crypto import Hash160
from ..utils.misc import BytesUtils
@unique
class P2PKHPubKeyModes(Enum):
"""Enumerative for P2PKH public key modes."""
COMPRESSED = auto()
UNCOMPRESSED = auto()
class P2PKHAddrDecoder(IAddrDecoder):
"""
P2PKH address decoder class.
It allows the Pay-to-Public-Key-Hash address decoding.
"""
@staticmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode a P2PKH address to bytes.
Args:
addr (str): Address string
Other Parameters:
net_ver (bytes) : Expected net address version
base58_alph (Base58Alphabets, optional): Base58 alphabet (default: Bitcoin alphabet)
Returns:
bytes: Public key hash bytes
Raises:
ValueError: If the address encoding is not valid
"""
net_ver_bytes = kwargs["net_ver"]
base58_alph = kwargs.get("base58_alph", Base58Alphabets.BITCOIN)
try:
addr_dec_bytes = Base58Decoder.CheckDecode(addr, base58_alph)
except Base58ChecksumError as ex:
raise ValueError("Invalid base58 checksum") from ex
# Validate length
AddrDecUtils.ValidateLength(addr_dec_bytes,
Hash160.DigestSize() + len(net_ver_bytes))
# Validate and remove prefix
return AddrDecUtils.ValidateAndRemovePrefix(addr_dec_bytes, net_ver_bytes)
class P2PKHAddrEncoder(IAddrEncoder):
"""
P2PKH address encoder class.
It allows the Pay-to-Public-Key-Hash address encoding.
"""
@staticmethod
def EncodeKey(pub_key: Union[bytes, IPublicKey],
**kwargs: Any) -> str:
"""
Encode a public key to P2PKH address.
Args:
pub_key (bytes or IPublicKey): Public key bytes or object
Other Parameters:
net_ver (bytes) : Net address version
base58_alph (Base58Alphabets, optional) : Base58 alphabet, Bitcoin alphabet by default
pub_key_mode (P2PKHPubKeyModes, optional): Public key mode, compressed key by default
Returns:
str: Address string
Raises:
ValueError: If the public key is not valid
TypeError: If the public key is not secp256k1
"""
net_ver_bytes = kwargs["net_ver"]
base58_alph = kwargs.get("base58_alph", Base58Alphabets.BITCOIN)
pub_key_mode = kwargs.get("pub_key_mode", P2PKHPubKeyModes.COMPRESSED)
pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
pub_key_bytes = (pub_key_obj.RawCompressed().ToBytes()
if pub_key_mode == P2PKHPubKeyModes.COMPRESSED
else pub_key_obj.RawUncompressed().ToBytes())
return Base58Encoder.CheckEncode(net_ver_bytes + Hash160.QuickDigest(pub_key_bytes), base58_alph)
class BchP2PKHAddrDecoder(IAddrDecoder):
"""
Bitcoin Cash P2PKH address decoder class.
It allows the Bitcoin Cash P2PKH decoding.
"""
@staticmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode a Bitcoin Cash P2PKH address to bytes.
Args:
addr (str): Address string
Other Parameters:
hrp (str) : Expected HRP
net_ver (bytes): Expected net address version
Returns:
bytes: Public key hash bytes
Raises:
ValueError: If the address encoding is not valid
"""
hrp = kwargs["hrp"]
net_ver_bytes = kwargs["net_ver"]
try:
net_ver_bytes_got, addr_dec_bytes = BchBech32Decoder.Decode(hrp, addr)
except Bech32ChecksumError as ex:
raise ValueError("Invalid bech32 checksum") from ex
# Check net version
if net_ver_bytes != net_ver_bytes_got:
raise ValueError(f"Invalid net version (expected {BytesUtils.ToHexString(net_ver_bytes)}, "
f"got {BytesUtils.ToHexString(net_ver_bytes_got)})")
# Validate length
AddrDecUtils.ValidateLength(addr_dec_bytes,
Hash160.DigestSize())
return addr_dec_bytes
class BchP2PKHAddrEncoder(IAddrEncoder):
"""
Bitcoin Cash P2PKH address encoder class.
It allows the Bitcoin Cash P2PKH encoding.
"""
@staticmethod
def EncodeKey(pub_key: Union[bytes, IPublicKey],
**kwargs: Any) -> str:
"""
Encode a public key to Bitcoin Cash P2PKH address.
Args:
pub_key (bytes or IPublicKey): Public key bytes or object
Other Parameters:
hrp (str) : HRP
net_ver (bytes): Net address version
Returns:
str: Address string
Raises:
ValueError: If the public key is not valid
TypeError: If the public key is not secp256k1
"""
hrp = kwargs["hrp"]
net_ver_bytes = kwargs["net_ver"]
pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
return BchBech32Encoder.Encode(hrp,
net_ver_bytes,
Hash160.QuickDigest(pub_key_obj.RawCompressed().ToBytes()))
# Deprecated: only for compatibility, Encoder classes shall be used instead
P2PKHAddr = P2PKHAddrEncoder
BchP2PKHAddr = BchP2PKHAddrEncoder
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/addr/P2PKH_addr.py",
"license": "MIT License",
"lines": 162,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/addr_dec_utils.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with utility functions for address decoding."""
# Imports
from typing import Callable, Tuple, Type, TypeVar, Union
from ..ecc import IPublicKey
from ..utils.misc import BytesUtils
BytesOrStr = TypeVar("BytesOrStr", bytes, str)
class AddrDecUtils:
"""Class container for address decoding utility functions."""
@staticmethod
def ValidateAndRemovePrefix(addr: BytesOrStr,
prefix: BytesOrStr) -> BytesOrStr:
"""
Validate and remove prefix from an address.
Args:
addr (bytes or str) : Address string or bytes
prefix (bytes or str): Address prefix
Returns:
bytes or str: Address string or bytes with prefix removed
Raises:
ValueError: If the prefix is not valid
"""
prefix_got = addr[:len(prefix)]
if prefix != prefix_got:
raise ValueError(f"Invalid prefix (expected {prefix!r}, got {prefix_got!r})")
return addr[len(prefix):]
@staticmethod
def ValidateLength(addr: Union[bytes, str],
len_exp: int) -> None:
"""
Validate address length.
Args:
addr (str) : Address string or bytes
len_exp (int): Expected address length
Raises:
ValueError: If the length is not valid
"""
if len(addr) != len_exp:
raise ValueError(f"Invalid length (expected {len_exp}, got {len(addr)})")
@staticmethod
def ValidatePubKey(pub_key_bytes: bytes,
pub_key_cls: Type[IPublicKey]) -> None:
"""
Validate address length.
Args:
pub_key_bytes (bytes) : Public key bytes
pub_key_cls (IPublicKey): Public key class type
Raises:
ValueError: If the public key is not valid
"""
if not pub_key_cls.IsValidBytes(pub_key_bytes):
raise ValueError(f"Invalid {pub_key_cls.CurveType()} "
f"public key {BytesUtils.ToHexString(pub_key_bytes)}")
@staticmethod
def ValidateChecksum(payload_bytes: bytes,
checksum_bytes_exp: bytes,
checksum_fct: Callable[[bytes], bytes]) -> None:
"""
Validate address checksum.
Args:
payload_bytes (bytes) : Payload bytes
checksum_bytes_exp (bytes): Expected checksum bytes
checksum_fct (function) : Function for computing checksum
Raises:
ValueError: If the computed checksum is not equal tot he specified one
"""
checksum_bytes_got = checksum_fct(payload_bytes)
if checksum_bytes_exp != checksum_bytes_got:
raise ValueError(f"Invalid checksum (expected {BytesUtils.ToHexString(checksum_bytes_exp)}, "
f"got {BytesUtils.ToHexString(checksum_bytes_got)})")
@staticmethod
def SplitPartsByChecksum(addr_bytes: bytes,
checksum_len: int) -> Tuple[bytes, bytes]:
"""
Split address in two parts, considering the checksum at the end of it.
Args:
addr_bytes (bytes): Address bytes
checksum_len (int): Checksum length
Returns:
tuple[bytes, bytes]: Payload bytes (index 0) and checksum bytes (index 1)
"""
checksum_bytes = addr_bytes[-1 * checksum_len:]
payload_bytes = addr_bytes[:-1 * checksum_len]
return payload_bytes, checksum_bytes
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/addr/addr_dec_utils.py",
"license": "MIT License",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/addr_key_validator.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with utility functions for validating address public keys."""
# Imports
from typing import Type, Union
from ..ecc import (
Secp256k1PublicKey, IPublicKey,
# Ed25519Blake2bPublicKey, Ed25519MoneroPublicKey, Ed25519PublicKey, EllipticCurveGetter,
# Nist256p1PublicKey, Secp256k1PublicKey, Sr25519PublicKey
)
class AddrKeyValidator:
"""Class container for address utility functions."""
# @staticmethod
# def ValidateAndGetEd25519Key(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
# """
# Validate and get a ed25519 public key.
# Args:
# pub_key (bytes or IPublicKey object): Public key bytes or object
# Returns:
# IPublicKey object: IPublicKey object
# Raises:
# TypeError: If the public key is not ed25519
# ValueError: If the public key is not valid
# """
# return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Ed25519PublicKey)
# @staticmethod
# def ValidateAndGetEd25519Blake2bKey(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
# """
# Validate and get a ed25519-blake2b public key.
# Args:
# pub_key (bytes or IPublicKey object): Public key bytes or object
# Returns:
# IPublicKey object: IPublicKey object
# Raises:
# TypeError: If the public key is not ed25519-blake2b
# ValueError: If the public key is not valid
# """
# return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Ed25519Blake2bPublicKey)
# @staticmethod
# def ValidateAndGetEd25519MoneroKey(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
# """
# Validate and get a ed25519-monero public key.
# Args:
# pub_key (bytes or IPublicKey object): Public key bytes or object
# Returns:
# IPublicKey object: IPublicKey object
# Raises:
# TypeError: If the public key is not ed25519-monero
# ValueError: If the public key is not valid
# """
# return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Ed25519MoneroPublicKey)
# @staticmethod
# def ValidateAndGetNist256p1Key(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
# """
# Validate and get a nist256p1 public key.
# Args:
# pub_key (bytes or IPublicKey object): Public key bytes or object
# Returns:
# IPublicKey object: IPublicKey object
# Raises:
# TypeError: If the public key is not nist256p1
# ValueError: If the public key is not valid
# """
# return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Nist256p1PublicKey)
@staticmethod
def ValidateAndGetSecp256k1Key(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
"""
Validate and get a secp256k1 public key.
Args:
pub_key (bytes or IPublicKey object): Public key bytes or object
Returns:
IPublicKey object: IPublicKey object
Raises:
TypeError: If the public key is not secp256k1
ValueError: If the public key is not valid
"""
return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Secp256k1PublicKey)
# @staticmethod
# def ValidateAndGetSr25519Key(pub_key: Union[bytes, IPublicKey]) -> IPublicKey:
# """
# Validate and get a sr25519 public key.
# Args:
# pub_key (bytes or IPublicKey object): Public key bytes or object
# Returns:
# IPublicKey object: IPublicKey object
# Raises:
# TypeError: If the public key is not sr25519
# ValueError: If the public key is not valid
# """
# return AddrKeyValidator.__ValidateAndGetGenericKey(pub_key, Sr25519PublicKey)
@staticmethod
def __ValidateAndGetGenericKey(pub_key: Union[bytes, IPublicKey],
pub_key_cls: Type[IPublicKey]) -> IPublicKey:
"""
Validate and get a generic public key.
Args:
pub_key (bytes or IPublicKey object): Public key bytes or object
pub_key_cls (IPublicKey) : Public key class type
Returns:
IPublicKey object: IPublicKey object
Raises:
TypeError: If the public key is not of the correct class type
ValueError: If the public key is not valid
"""
if isinstance(pub_key, bytes):
pub_key = pub_key_cls.FromBytes(pub_key)
elif not isinstance(pub_key, pub_key_cls):
curve = EllipticCurveGetter.FromType(pub_key_cls.CurveType())
raise TypeError(f"A {curve.Name()} public key is required"
f"(expected: {pub_key_cls}, got: {type(pub_key)}")
return pub_key
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/addr/addr_key_validator.py",
"license": "MIT License",
"lines": 128,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/iaddr_decoder.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with interface for address encoding classes."""
# Imports
from abc import ABC, abstractmethod
from typing import Any
class IAddrDecoder(ABC):
"""Address decoder interface."""
@staticmethod
@abstractmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode an address to bytes.
Depending on the coin, the result can be a public key or a public key hash bytes.
Args:
addr (str): Address string
**kwargs : Arbitrary arguments depending on the address type
Returns:
bytes: Public key bytes or public key hash
Raises:
ValueError: If the address encoding is not valid
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/addr/iaddr_decoder.py",
"license": "MIT License",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/iaddr_encoder.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with interface for address encoding classes."""
# Imports
from abc import ABC, abstractmethod
from typing import Any, Union
from ..ecc import IPublicKey
class IAddrEncoder(ABC):
"""Address encoder interface."""
@staticmethod
@abstractmethod
def EncodeKey(pub_key: Union[bytes, IPublicKey],
**kwargs: Any) -> str:
"""
Encode public key to address.
Args:
pub_key (bytes or IPublicKey): Public key bytes or object
**kwargs : Arbitrary arguments depending on the address type
Returns:
str: Address string
Raised:
ValueError: If the public key is not valid
TypeError: If the public key is not of the correct type (it depends on the address type)
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/addr/iaddr_encoder.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/base58/base58.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for base58 decoding/encoding."""
# Imports
from enum import Enum, auto, unique
from typing import Dict
from .base58_ex import Base58ChecksumError
from ..utils.crypto import DoubleSha256
from ..utils.misc import BytesUtils
@unique
class Base58Alphabets(Enum):
"""Enumerative for Base58 alphabet."""
BITCOIN = auto()
RIPPLE = auto()
class Base58Const:
"""Class container for Base58 constants."""
# Base58 radix
RADIX: int = 58
# Checksum length in bytes
CHECKSUM_BYTE_LEN: int = 4
# Alphabets
ALPHABETS: Dict[Base58Alphabets, str] = {
Base58Alphabets.BITCOIN: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
Base58Alphabets.RIPPLE: "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
}
class Base58Utils:
"""Class container for Base58 utility functions."""
@staticmethod
def ComputeChecksum(data_bytes: bytes) -> bytes:
"""
Compute Base58 checksum.
Args:
data_bytes (bytes): Data bytes
Returns:
bytes: Computed checksum
"""
return DoubleSha256.QuickDigest(data_bytes)[:Base58Const.CHECKSUM_BYTE_LEN]
class Base58Encoder:
"""Base58 encoder class. It provides methods for encoding and checksum encoding to Base58 format."""
@staticmethod
def Encode(data_bytes: bytes,
alph_idx: Base58Alphabets = Base58Alphabets.BITCOIN) -> str:
"""
Encode bytes into a Base58 string.
Args:
data_bytes (bytes) : Data bytes
alph_idx (Base58Alphabets, optional): Alphabet index, Bitcoin by default
Returns:
str: Encoded string
Raises:
TypeError: If alphabet index is not a Base58Alphabets enumerative
"""
if not isinstance(alph_idx, Base58Alphabets):
raise TypeError("Alphabet index is not an enumerative of Base58Alphabets")
enc = ""
# Get alphabet
alphabet = Base58Const.ALPHABETS[alph_idx]
# Convert bytes to integer
val = BytesUtils.ToInteger(data_bytes)
# Algorithm implementation
while val > 0:
val, mod = divmod(val, Base58Const.RADIX)
enc = alphabet[mod] + enc
# Get number of leading zeros
n = len(data_bytes) - len(data_bytes.lstrip(b"\x00"))
# Add padding
return (alphabet[0] * n) + enc
@staticmethod
def CheckEncode(data_bytes: bytes,
alph_idx: Base58Alphabets = Base58Alphabets.BITCOIN) -> str:
"""
Encode bytes into Base58 string with checksum.
Args:
data_bytes (bytes) : Data bytes
alph_idx (Base58Alphabets, optional): Alphabet index, Bitcoin by default
Returns:
str: Encoded string with checksum
Raises:
TypeError: If alphabet index is not a Base58Alphabets enumerative
"""
# Append checksum and encode all together
return Base58Encoder.Encode(data_bytes + Base58Utils.ComputeChecksum(data_bytes), alph_idx)
class Base58Decoder:
"""Base58 decoder class. It provides methods for decoding and checksum decoding Base58 format."""
@staticmethod
def Decode(data_str: str,
alph_idx: Base58Alphabets = Base58Alphabets.BITCOIN) -> bytes:
"""
Decode bytes from a Base58 string.
Args:
data_str (str) : Data string
alph_idx (Base58Alphabets, optional): Alphabet index, Bitcoin by default
Returns:
bytes: Decoded bytes
Raises:
TypeError: If alphabet index is not a Base58Alphabets enumerative
"""
if not isinstance(alph_idx, Base58Alphabets):
raise TypeError("Alphabet index is not an enumerative of Base58Alphabets")
# Get alphabet
alphabet = Base58Const.ALPHABETS[alph_idx]
# Convert string to integer
val = 0
for i, c in enumerate(data_str[::-1]):
val += alphabet.index(c) * (Base58Const.RADIX ** i)
dec = bytearray()
while val > 0:
val, mod = divmod(val, 2**8)
dec.append(mod)
# Get padding length
pad_len = len(data_str) - len(data_str.lstrip(alphabet[0]))
# Add padding
return (b"\x00" * pad_len) + bytes(dec[::-1])
@staticmethod
def CheckDecode(data_str: str,
alph_idx: Base58Alphabets = Base58Alphabets.BITCOIN) -> bytes:
"""
Decode bytes from a Base58 string with checksum.
Args:
data_str (str) : Data string
alph_idx (Base58Alphabets, optional): Alphabet index, Bitcoin by default
Returns:
bytes: Decoded bytes (checksum removed)
Raises:
ValueError: If the string is not a valid Base58 format
TypeError: If alphabet index is not a Base58Alphabets enumerative
Base58ChecksumError: If checksum is not valid
"""
# Decode string
dec_bytes = Base58Decoder.Decode(data_str, alph_idx)
# Get data and checksum bytes
data_bytes = dec_bytes[:-Base58Const.CHECKSUM_BYTE_LEN]
checksum_bytes = dec_bytes[-Base58Const.CHECKSUM_BYTE_LEN:]
# Compute checksum
checksum_bytes_got = Base58Utils.ComputeChecksum(data_bytes)
# Verify checksum
if checksum_bytes != checksum_bytes_got:
raise Base58ChecksumError(
f"Invalid checksum (expected {BytesUtils.ToHexString(checksum_bytes_got)}, "
f"got {BytesUtils.ToHexString(checksum_bytes)})"
)
return data_bytes
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/base58/base58.py",
"license": "MIT License",
"lines": 159,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/base58/base58_ex.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for base58 exceptions."""
class Base58ChecksumError(Exception):
"""Exception in case of checksum error."""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/base58/base58_ex.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/base58/base58_xmr.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for base58-monero decoding/encoding."""
# Imports
from typing import List
from .base58 import Base58Alphabets, Base58Const, Base58Decoder, Base58Encoder
class Base58XmrConst:
"""Class container for Base58 Monero constants."""
# Alphabet
ALPHABET: str = Base58Const.ALPHABETS[Base58Alphabets.BITCOIN]
# Block decoded maximum length in bytes
BLOCK_DEC_MAX_BYTE_LEN: int = 8
# Block encoded maximum length in bytes
BLOCK_ENC_MAX_BYTE_LEN: int = 11
# Block encoded lengths in bytes
BLOCK_ENC_BYTE_LENS: List[int] = [0, 2, 3, 5, 6, 7, 9, 10, 11]
class Base58XmrEncoder:
"""
Base58 Monero encoder class.
It provides methods for encoding to Base58 format with Monero variation (encoding by blocks of 8-byte).
"""
@staticmethod
def Encode(data_bytes: bytes) -> str:
"""
Encode bytes into a Base58 string with Monero variation.
Args:
data_bytes (bytes): Data bytes
Returns:
str: Encoded string
"""
enc = ""
# Get lengths
data_len = len(data_bytes)
block_dec_len = Base58XmrConst.BLOCK_DEC_MAX_BYTE_LEN
# Compute total block count and last block length
tot_block_cnt, last_block_enc_len = divmod(data_len, block_dec_len)
# Encode each single block and pad
for i in range(tot_block_cnt):
block_enc = Base58Encoder.Encode(data_bytes[i * block_dec_len:(i + 1) * block_dec_len])
enc += Base58XmrEncoder.__Pad(block_enc, Base58XmrConst.BLOCK_ENC_MAX_BYTE_LEN)
# Encode last block and pad
if last_block_enc_len > 0:
block_enc = Base58Encoder.Encode(
data_bytes[tot_block_cnt * block_dec_len:(tot_block_cnt * block_dec_len) + last_block_enc_len])
enc += Base58XmrEncoder.__Pad(block_enc, Base58XmrConst.BLOCK_ENC_BYTE_LENS[last_block_enc_len])
return enc
@staticmethod
def __Pad(enc_str: str,
pad_len: int) -> str:
"""
Pad the encoded string to the specified length.
Args:
enc_str (str): Encoded string
pad_len (int): Pad length
Returns:
str: Padded string
"""
return enc_str.rjust(pad_len, Base58XmrConst.ALPHABET[0])
class Base58XmrDecoder:
"""
Base58 Monero decoder class.
It provides methods for decoding Base58 format with Monero variation (encoding by blocks of 8-byte).
"""
@staticmethod
def Decode(data_str: str) -> bytes:
"""
Decode bytes from a Base58 string with Monero variation.
Args:
data_str (str): Data string
Returns:
bytes: Decoded bytes
"""
dec = b""
# Get lengths
data_len = len(data_str)
block_dec_len = Base58XmrConst.BLOCK_DEC_MAX_BYTE_LEN
block_enc_len = Base58XmrConst.BLOCK_ENC_MAX_BYTE_LEN
# Compute block count and last block length
tot_block_cnt, last_block_enc_len = divmod(data_len, block_enc_len)
# Get last block decoded length
last_block_dec_len = Base58XmrConst.BLOCK_ENC_BYTE_LENS.index(last_block_enc_len)
# Decode each single block and unpad
for i in range(tot_block_cnt):
block_dec = Base58Decoder.Decode(data_str[(i * block_enc_len):((i + 1) * block_enc_len)])
dec += Base58XmrDecoder.__UnPad(block_dec, block_dec_len)
# Decode last block and unpad
if last_block_enc_len > 0:
block_dec = Base58Decoder.Decode(
data_str[(tot_block_cnt * block_enc_len):((tot_block_cnt * block_enc_len) + last_block_enc_len)])
dec += Base58XmrDecoder.__UnPad(block_dec, last_block_dec_len)
return dec
@staticmethod
def __UnPad(dec_bytes: bytes,
unpad_len: int) -> bytes:
"""
Unpad the decoded string to the specified length.
Args:
dec_bytes (bytes): Decoded bytes
unpad_len (int): Unpad length
Returns:
bytes: Unpadded string
"""
return dec_bytes[len(dec_bytes) - unpad_len:len(dec_bytes)]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/base58/base58_xmr.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/bch_bech32.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BitcoinCash bech32 decoding/encoding.
Reference: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md
"""
# Imports
from typing import List, Tuple
from .bech32_base import Bech32BaseUtils, Bech32DecoderBase, Bech32EncoderBase
from ..utils.misc import BytesUtils, IntegerUtils
class BchBech32Const:
"""Class container for Bitcoin Cash Bech32 constants."""
# Separator
SEPARATOR: str = ":"
# Checksum length
CHECKSUM_STR_LEN: int = 8
class BchBech32Utils:
"""Class container for Bitcoin Cash utility functions."""
@staticmethod
def PolyMod(values: List[int]) -> int:
"""
Computes the polynomial modulus.
Args:
values (list[int]): List of polynomial coefficients
Returns:
int: Computed modulus
"""
# Generator polynomial
generator = [
(0x01, 0x98f2bc8e61),
(0x02, 0x79b76d99e2),
(0x04, 0xf33e5fb3c4),
(0x08, 0xae2eabe2a8),
(0x10, 0x1e4f43e470)
]
# Compute modulus
chk = 1
for value in values:
top = chk >> 35
chk = ((chk & 0x07ffffffff) << 5) ^ value
for i in generator:
if top & i[0] != 0:
chk ^= i[1]
return chk ^ 1
@staticmethod
def HrpExpand(hrp: str) -> List[int]:
"""
Expand the HRP into values for checksum computation.
Args:
hrp (str): HRP
Returns:
list[int]: Expanded HRP values
"""
# [lower 5 bits of each character] + [0]
return [ord(x) & 0x1f for x in hrp] + [0]
@staticmethod
def ComputeChecksum(hrp: str,
data: List[int]) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
list[int]: Computed checksum
"""
values = BchBech32Utils.HrpExpand(hrp) + data
polymod = BchBech32Utils.PolyMod(values + [0, 0, 0, 0, 0, 0, 0, 0])
return [(polymod >> 5 * (7 - i)) & 0x1f for i in range(BchBech32Const.CHECKSUM_STR_LEN)]
@staticmethod
def VerifyChecksum(hrp: str,
data: List[int]) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
bool: True if valid, false otherwise
"""
return BchBech32Utils.PolyMod(BchBech32Utils.HrpExpand(hrp) + data) == 0
class BchBech32Encoder(Bech32EncoderBase):
"""
Bitcoin Cash Bech32 encoder class.
It provides methods for encoding to Bitcoin Cash Bech32 format.
"""
@classmethod
def Encode(cls,
hrp: str,
net_ver: bytes,
data: bytes) -> str:
"""
Encode to Bitcoin Cash Bech32.
Args:
hrp (str) : HRP
net_ver (bytes): Net version
data (bytes) : Data
Returns:
str: Encoded address
Raises:
ValueError: If the data is not valid
"""
return cls._EncodeBech32(hrp,
Bech32BaseUtils.ConvertToBase32(net_ver + data),
BchBech32Const.SEPARATOR)
@staticmethod
def _ComputeChecksum(hrp: str,
data: List[int]) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
list[int]: Computed checksum
"""
return BchBech32Utils.ComputeChecksum(hrp, data)
class BchBech32Decoder(Bech32DecoderBase):
"""
Bitcoin Cash Bech32 decoder class.
It provides methods for decoding Bitcoin Cash Bech32 format.
"""
@classmethod
def Decode(cls,
hrp: str,
addr: str) -> Tuple[bytes, bytes]:
"""
Decode from Bitcoin Cash Bech32.
Args:
hrp (str) : Human readable part
addr (str): Address
Returns:
tuple[bytes, bytes]: Net version (index 0) and data (index 1)
Raises:
ValueError: If the bech32 string is not valid
Bech32ChecksumError: If the checksum is not valid
"""
# Decode string
hrp_got, data = cls._DecodeBech32(addr,
BchBech32Const.SEPARATOR,
BchBech32Const.CHECKSUM_STR_LEN)
# Check HRP
if hrp != hrp_got:
raise ValueError(f"Invalid format (HRP not valid, expected {hrp}, got {hrp_got})")
# Convert back from base32
conv_data = Bech32BaseUtils.ConvertFromBase32(data)
return IntegerUtils.ToBytes(conv_data[0]), BytesUtils.FromList(conv_data[1:])
@staticmethod
def _VerifyChecksum(hrp: str,
data: List[int]) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
bool: True if valid, false otherwise
"""
return BchBech32Utils.VerifyChecksum(hrp, data)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bech32/bch_bech32.py",
"license": "MIT License",
"lines": 176,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/bech32.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for bech32/bech32m decoding/encoding.
References:
https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
"""
# Imports
from enum import Enum, auto, unique
from typing import Dict, List
from .bech32_base import Bech32BaseUtils, Bech32DecoderBase, Bech32EncoderBase
from ..utils.misc import BytesUtils
@unique
class Bech32Encodings(Enum):
"""Enumerative for Bech32 encoding types."""
BECH32 = auto()
BECH32M = auto()
class Bech32Const:
"""Class container for Bech32 constants."""
# Separator
SEPARATOR: str = "1"
# Checksum length
CHECKSUM_STR_LEN: int = 6
# Encoding checksum constants
ENCODING_CHECKSUM_CONST: Dict[Bech32Encodings, int] = {
Bech32Encodings.BECH32: 1,
Bech32Encodings.BECH32M: 0x2bc830a3,
}
class Bech32Utils:
"""Class container for Bech32 utility functions."""
@staticmethod
def PolyMod(values: List[int]) -> int:
"""
Computes the polynomial modulus.
Args:
values (list[int]): List of polynomial coefficients
Returns:
int: Computed modulus
"""
# Generator polynomial
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
# Compute modulus
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
chk ^= generator[i] if ((top >> i) & 1) else 0
return chk
@staticmethod
def HrpExpand(hrp: str) -> List[int]:
"""
Expand the HRP into values for checksum computation.
Args:
hrp (str): HRP
Returns:
list[int]: Expanded HRP values
"""
# [upper 3 bits of each character] + [0] + [lower 5 bits of each character]
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 0x1f for x in hrp]
@staticmethod
def ComputeChecksum(hrp: str,
data: List[int],
encoding: Bech32Encodings = Bech32Encodings.BECH32) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]) : Data part
encoding (Bech32Encodings, optional): Encoding type (BECH32 by default)
Returns:
list[int]: Computed checksum
"""
values = Bech32Utils.HrpExpand(hrp) + data
polymod = Bech32Utils.PolyMod(values + [0, 0, 0, 0, 0, 0]) ^ Bech32Const.ENCODING_CHECKSUM_CONST[encoding]
return [(polymod >> 5 * (5 - i)) & 0x1f for i in range(Bech32Const.CHECKSUM_STR_LEN)]
@staticmethod
def VerifyChecksum(hrp: str,
data: List[int],
encoding: Bech32Encodings = Bech32Encodings.BECH32) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]) : Data part
encoding (Bech32Encodings, optional): Encoding type (BECH32 by default)
Returns:
bool: True if valid, false otherwise
"""
polymod = Bech32Utils.PolyMod(Bech32Utils.HrpExpand(hrp) + data)
return polymod == Bech32Const.ENCODING_CHECKSUM_CONST[encoding]
class Bech32Encoder(Bech32EncoderBase):
"""
Bech32 encoder class.
It provides methods for encoding to Bech32 format.
"""
@classmethod
def Encode(cls,
hrp: str,
data: bytes) -> str:
"""
Encode to Bech32.
Args:
hrp (str) : HRP
data (bytes): Data
Returns:
str: Encoded address
Raises:
ValueError: If the data is not valid
"""
return cls._EncodeBech32(hrp,
Bech32BaseUtils.ConvertToBase32(data),
Bech32Const.SEPARATOR)
@staticmethod
def _ComputeChecksum(hrp: str,
data: List[int]) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
list[int]: Computed checksum
"""
# Same as Segwit
return Bech32Utils.ComputeChecksum(hrp, data)
class Bech32Decoder(Bech32DecoderBase):
"""
Bech32 decoder class.
It provides methods for decoding Bech32 format.
"""
@classmethod
def Decode(cls,
hrp: str,
addr: str) -> bytes:
"""
Decode from Bech32.
Args:
hrp (str) : Human readable part
addr (str): Address
Returns:
bytes: Decoded address
Raises:
ValueError: If the bech32 string is not valid
Bech32ChecksumError: If the checksum is not valid
"""
# Decode string
hrp_got, data = cls._DecodeBech32(addr,
Bech32Const.SEPARATOR,
Bech32Const.CHECKSUM_STR_LEN)
# Check HRP
if hrp != hrp_got:
raise ValueError(f"Invalid format (HRP not valid, expected {hrp}, got {hrp_got})")
# Convert back from base32
return BytesUtils.FromList(
Bech32BaseUtils.ConvertFromBase32(data)
)
@staticmethod
def _VerifyChecksum(hrp: str,
data: List[int]) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
bool: True if valid, false otherwise
"""
return Bech32Utils.VerifyChecksum(hrp, data)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bech32/bech32.py",
"license": "MIT License",
"lines": 188,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/bech32_base.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for base bech32 decoding/encoding."""
# Imports
from abc import ABC, abstractmethod
from typing import List, Optional, Tuple, Union
from .bech32_ex import Bech32ChecksumError
from ..utils.misc import AlgoUtils
class Bech32BaseConst:
"""Class container for Bech32 constants."""
# Character set
CHARSET: str = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
class Bech32BaseUtils:
"""Class container for Bech32 utility functions."""
@staticmethod
def ConvertToBase32(data: Union[List[int], bytes]) -> List[int]:
"""
Convert data to base32.
Args:
data (list[int] or bytes): Data to be converted
Returns:
list[int]: Converted data
Raises:
ValueError: If the string is not valid
"""
# Convert to base32
conv_data = Bech32BaseUtils.ConvertBits(data, 8, 5)
if conv_data is None:
raise ValueError("Invalid data, cannot perform conversion to base32")
return conv_data
@staticmethod
def ConvertFromBase32(data: Union[List[int], bytes]) -> List[int]:
"""
Convert data from base32.
Args:
data (list[int] or bytes): Data to be converted
Returns:
list[int]: Converted data
Raises:
ValueError: If the string is not valid
"""
# Convert from base32
conv_data = Bech32BaseUtils.ConvertBits(data, 5, 8, False)
if conv_data is None:
raise ValueError("Invalid data, cannot perform conversion from base32")
return conv_data
@staticmethod
def ConvertBits(data: Union[bytes, List[int]],
from_bits: int,
to_bits: int,
pad: bool = True) -> Optional[List[int]]:
"""
Perform bit conversion.
The function takes the input data (list of integers or byte sequence) and convert every value from
the specified number of bits to the specified one.
It returns a list of integer where every number is less than 2^to_bits.
Args:
data (list[int] or bytes): Data to be converted
from_bits (int) : Number of bits to start from
to_bits (int) : Number of bits to end with
pad (bool, optional) : True if data must be padded with zeros, false otherwise
Returns:
list[int]: List of converted values, None in case of errors
"""
max_out_val = (1 << to_bits) - 1
max_acc = (1 << (from_bits + to_bits - 1)) - 1
acc = 0
bits = 0
ret = []
for value in data:
# Value shall not be less than zero or greater than 2^from_bits
if value < 0 or (value >> from_bits):
return None
# Continue accumulating until greater than to_bits
acc = ((acc << from_bits) | value) & max_acc
bits += from_bits
while bits >= to_bits:
bits -= to_bits
ret.append((acc >> bits) & max_out_val)
if pad:
if bits:
# Pad the value with zeros to reach to_bits
ret.append((acc << (to_bits - bits)) & max_out_val)
elif bits >= from_bits or ((acc << (to_bits - bits)) & max_out_val):
return None
return ret
class Bech32EncoderBase(ABC):
"""
Bech32 encoder base class.
It provides methods for encoding to Bech32 format.
"""
@classmethod
def _EncodeBech32(cls,
hrp: str,
data: List[int],
sep: str) -> str:
"""
Encode a Bech32 string from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
sep (str) : Bech32 separator
Returns:
str: Encoded data
"""
# Add checksum to data
data += cls._ComputeChecksum(hrp, data)
# Encode to alphabet
return hrp + sep + "".join([Bech32BaseConst.CHARSET[d] for d in data])
@staticmethod
@abstractmethod
def _ComputeChecksum(hrp: str,
data: List[int]) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
list[int]: Computed checksum
"""
class Bech32DecoderBase(ABC):
"""
Bech32 decoder base class.
It provides methods for decoding Bech32 format.
"""
@classmethod
def _DecodeBech32(cls,
bech_str: str,
sep: str,
checksum_len: int) -> Tuple[str, List[int]]:
"""
Decode and validate a Bech32 string, determining its HRP and data.
Args:
bech_str (str) : Bech32 string
sep (str) : Bech32 separator
checksum_len (int): Checksum length
Returns:
tuple[str, list[int]]: HRP (index 0) and data part (index 1)
Raises:
ValueError: If the string is not valid
Bech32ChecksumError: If the checksum is not valid
"""
# Check string length and case
if AlgoUtils.IsStringMixed(bech_str):
raise ValueError("Invalid bech32 format (string is mixed case)")
# Lower string
bech_str = bech_str.lower()
# Find separator and check its position
sep_pos = bech_str.rfind(sep)
if sep_pos == -1:
raise ValueError("Invalid bech32 format (no separator found)")
# Get HRP and check it
hrp = bech_str[:sep_pos]
if len(hrp) == 0 or any(ord(x) < 33 or ord(x) > 126 for x in hrp):
raise ValueError(f"Invalid bech32 format (HRP not valid: {hrp})")
# Get data and check it
data_part = bech_str[sep_pos + 1:]
if (len(data_part) < (checksum_len + 1)
or not all(x in Bech32BaseConst.CHARSET for x in data_part)):
raise ValueError("Invalid bech32 format (data part not valid)")
# Convert back from alphabet and verify checksum
int_data = [Bech32BaseConst.CHARSET.find(x) for x in data_part]
if not cls._VerifyChecksum(hrp, int_data):
raise Bech32ChecksumError("Invalid bech32 checksum")
return hrp, int_data[:-checksum_len]
@staticmethod
@abstractmethod
def _VerifyChecksum(hrp: str,
data: List[int]) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
bool: True if valid, false otherwise
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bech32/bech32_base.py",
"license": "MIT License",
"lines": 195,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/bech32_ex.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for bech32 exceptions."""
class Bech32ChecksumError(Exception):
"""Exception in case of checksum error."""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bech32/bech32_ex.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/segwit_bech32.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for segwit bech32/bech32m decoding/encoding.
References:
https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
"""
# Imports
from typing import List, Tuple
from .bech32 import Bech32Const, Bech32Encodings, Bech32Utils
from .bech32_base import Bech32BaseUtils, Bech32DecoderBase, Bech32EncoderBase
from ..utils.misc import BytesUtils
class SegwitBech32Const:
"""Class container for Segwit Bech32 constants."""
# Separator
SEPARATOR: str = Bech32Const.SEPARATOR
# Checksum length
CHECKSUM_STR_LEN: int = Bech32Const.CHECKSUM_STR_LEN
# Minimum witness program length in bytes
WITNESS_PROG_MIN_BYTE_LEN: int = 2
# Maximum witness program length in bytes
WITNESS_PROG_MAX_BYTE_LEN: int = 40
# Witness version for Bech32 encoding
WITNESS_VER_BECH32: int = 0
# Witness version maximum value
WITNESS_VER_MAX_VAL: int = 16
# Accepted data lengths when witness version is zero
WITNESS_VER_ZERO_DATA_BYTE_LEN: Tuple[int, int] = (20, 32)
class SegwitBech32Encoder(Bech32EncoderBase):
"""
Segwit Bech32 encoder class.
It provides methods for encoding to Segwit Bech32 format.
"""
@classmethod
def Encode(cls,
hrp: str,
wit_ver: int,
wit_prog: bytes) -> str:
"""
Encode to Segwit Bech32.
Args:
hrp (str) : HRP
wit_ver (int) : Witness version
wit_prog (bytes): Witness program
Returns:
str: Encoded address
Raises:
ValueError: If the data is not valid
"""
return cls._EncodeBech32(hrp,
[wit_ver] + Bech32BaseUtils.ConvertToBase32(wit_prog),
SegwitBech32Const.SEPARATOR)
@staticmethod
def _ComputeChecksum(hrp: str,
data: List[int]) -> List[int]:
"""
Compute the checksum from the specified HRP and data.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
list[int]: Computed checksum
"""
encoding = (Bech32Encodings.BECH32
if data[0] == SegwitBech32Const.WITNESS_VER_BECH32
else Bech32Encodings.BECH32M)
return Bech32Utils.ComputeChecksum(hrp, data, encoding)
class SegwitBech32Decoder(Bech32DecoderBase):
"""
Segwit Bech32 decoder class.
It provides methods for decoding Segwit Bech32 format.
"""
@classmethod
def Decode(cls,
hrp: str,
addr: str) -> Tuple[int, bytes]:
"""
Decode from Segwit Bech32.
Args:
hrp (str) : Human readable part
addr (str): Address
Returns:
tuple[int, bytes]: Witness version (index 0) and witness program (index 1)
Raises:
Bech32ChecksumError: If the checksum is not valid
ValueError: If the bech32 string is not valid
"""
# Decode string
hrp_got, data = cls._DecodeBech32(addr,
SegwitBech32Const.SEPARATOR,
SegwitBech32Const.CHECKSUM_STR_LEN)
# Check HRP
if hrp != hrp_got:
raise ValueError(
f"Invalid format (HRP not valid, expected {hrp}, got {hrp_got})"
)
# Convert back from base32 (remove witness version)
conv_data = Bech32BaseUtils.ConvertFromBase32(data[1:])
# Check data length
if (len(conv_data) < SegwitBech32Const.WITNESS_PROG_MIN_BYTE_LEN
or len(conv_data) > SegwitBech32Const.WITNESS_PROG_MAX_BYTE_LEN):
raise ValueError(f"Invalid format (witness program length not valid: {len(conv_data)})")
# Check witness version
wit_ver = data[0]
if wit_ver > SegwitBech32Const.WITNESS_VER_MAX_VAL:
raise ValueError(f"Invalid format (witness version not valid: {wit_ver})")
if wit_ver == 0 and not len(conv_data) in SegwitBech32Const.WITNESS_VER_ZERO_DATA_BYTE_LEN:
raise ValueError(f"Invalid format (length not valid: {len(conv_data)})")
return wit_ver, BytesUtils.FromList(conv_data)
@staticmethod
def _VerifyChecksum(hrp: str,
data: List[int]) -> bool:
"""
Verify the checksum from the specified HRP and converted data characters.
Args:
hrp (str) : HRP
data (list[int]): Data part
Returns:
bool: True if valid, false otherwise
"""
encoding = (Bech32Encodings.BECH32
if data[0] == SegwitBech32Const.WITNESS_VER_BECH32
else Bech32Encodings.BECH32M)
return Bech32Utils.VerifyChecksum(hrp, data, encoding)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bech32/segwit_bech32.py",
"license": "MIT License",
"lines": 142,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/base/bip32_base.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with BIP32 base class."""
# Imports
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional, Type, Union
from .ibip32_key_derivator import IBip32KeyDerivator
from .ibip32_mst_key_generator import IBip32MstKeyGenerator
from ..bip32_ex import Bip32KeyError
from ..bip32_key_data import Bip32ChainCode, Bip32Depth, Bip32FingerPrint, Bip32KeyData, Bip32KeyIndex
from ..bip32_key_net_ver import Bip32KeyNetVersions
from ..bip32_key_ser import Bip32KeyDeserializer
from ..bip32_keys import Bip32PrivateKey, Bip32PublicKey
from ..bip32_path import Bip32Path, Bip32PathParser
from ...ecc import EllipticCurve, EllipticCurveGetter, EllipticCurveTypes, IPoint, IPrivateKey, IPublicKey
class Bip32Base(ABC):
"""
BIP32 base class.
It allows master key generation and children keys derivation in according to BIP-0032/SLIP-0010.
It shall be derived to implement derivation for a specific elliptic curve.
"""
m_priv_key: Optional[Bip32PrivateKey]
m_pub_key: Bip32PublicKey
#
# Class methods for construction
#
@classmethod
def FromSeed(cls,
seed_bytes: bytes,
key_net_ver: Optional[Bip32KeyNetVersions] = None) -> Bip32Base:
"""
Create a Bip32 object from the specified seed (e.g. BIP39 seed).
Args:
seed_bytes (bytes) : Seed bytes
key_net_ver (Bip32KeyNetVersions object, optional): Bip32KeyNetVersions object
(default: specific class key net version)
Returns:
Bip32Base object: Bip32Base object
Raises:
ValueError: If the seed is too short
Bip32KeyError: If the seed is not suitable for master key generation
"""
priv_key_bytes, chain_code_bytes = cls._MasterKeyGenerator().GenerateFromSeed(seed_bytes)
return cls(
priv_key=priv_key_bytes,
pub_key=None,
key_data=Bip32KeyData(chain_code=chain_code_bytes),
key_net_ver=key_net_ver or cls._DefaultKeyNetVersion()
)
@classmethod
def FromSeedAndPath(cls,
seed_bytes: bytes,
path: Union[str, Bip32Path],
key_net_ver: Optional[Bip32KeyNetVersions] = None) -> Bip32Base:
"""
Create a Bip32 object from the specified seed (e.g. BIP39 seed) and path.
Args:
seed_bytes (bytes) : Seed bytes
path (str or Bip32Path object) : Path
key_net_ver (Bip32KeyNetVersions object, optional): Bip32KeyNetVersions object
(default: specific class key net version)
Returns:
Bip32Base object: Bip32Base object
Raises:
ValueError: If the seed length is too short
Bip32PathError: If the path is not valid
Bip32KeyError: If the seed is not suitable for master key generation
"""
key_net_ver = key_net_ver or cls._DefaultKeyNetVersion()
return cls.FromSeed(seed_bytes, key_net_ver).DerivePath(path)
@classmethod
def FromExtendedKey(cls,
ex_key_str: str,
key_net_ver: Optional[Bip32KeyNetVersions] = None) -> Bip32Base:
"""
Create a Bip32 object from the specified extended key.
Args:
ex_key_str (str) : Extended key string
key_net_ver (Bip32KeyNetVersions object, optional): Bip32KeyNetVersions object
(default: specific class key net version)
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the key is not valid
"""
key_net_ver = key_net_ver or cls._DefaultKeyNetVersion()
# De-serialize key
deser_key = Bip32KeyDeserializer.DeserializeKey(ex_key_str, key_net_ver)
# Get key parts
key_bytes, key_data, is_public = deser_key.KeyBytes(), deser_key.KeyData(), deser_key.IsPublic()
# If depth is zero, fingerprint shall be the master one and child index shall be zero
if key_data.Depth() == 0:
if not key_data.ParentFingerPrint().IsMasterKey():
raise Bip32KeyError(
f"Invalid extended master key (wrong fingerprint: {key_data.ParentFingerPrint().ToHex()})"
)
if key_data.Index() != 0:
raise Bip32KeyError(f"Invalid extended master key (wrong child index: {key_data.Index().ToInt()})")
return cls(
priv_key=key_bytes if not is_public else None,
pub_key=key_bytes if is_public else None,
key_data=key_data,
key_net_ver=key_net_ver
)
@classmethod
def FromPrivateKey(cls,
priv_key: Union[bytes, IPrivateKey],
key_data: Bip32KeyData = Bip32KeyData(),
key_net_ver: Optional[Bip32KeyNetVersions] = None) -> Bip32Base:
"""
Create a Bip32 object from the specified private key and derivation data.
If only the private key bytes are specified, the key will be considered a master key with
the chain code set to zero, since there is no way to recover the key derivation data.
Args:
priv_key (bytes or IPrivateKey) : Private key
key_data (Bip32KeyData object, optional) : Key data (default: all zeros)
key_net_ver (Bip32KeyNetVersions object, optional): Bip32KeyNetVersions object
(default: specific class key net version)
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the key is not valid
"""
return cls(
priv_key=priv_key,
pub_key=None,
key_data=key_data,
key_net_ver=key_net_ver or cls._DefaultKeyNetVersion()
)
@classmethod
def FromPublicKey(cls,
pub_key: Union[bytes, IPoint, IPublicKey],
key_data: Bip32KeyData = Bip32KeyData(),
key_net_ver: Optional[Bip32KeyNetVersions] = None) -> Bip32Base:
"""
Create a Bip32 object from the specified public key and derivation data.
If only the public key bytes are specified, the key will be considered a master key with
the chain code set to zero, since there is no way to recover the key derivation data.
Args:
pub_key (bytes, IPoint or IPublicKey) : Public key
key_data (Bip32KeyData object, optional) : Key data (default: all zeros)
key_net_ver (Bip32KeyNetVersions object, optional): Bip32KeyNetVersions object
(default: specific class key net version)
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the key is not valid
"""
return cls(
priv_key=None,
pub_key=pub_key,
key_data=key_data,
key_net_ver=key_net_ver or cls._DefaultKeyNetVersion()
)
#
# Public methods
#
def __init__(self,
priv_key: Optional[Union[bytes, IPrivateKey]],
pub_key: Optional[Union[bytes, IPoint, IPublicKey]],
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions) -> None:
"""
Construct class.
Args:
priv_key (bytes or IPrivateKey) : Private key (None for a public-only object)
pub_key (bytes, IPoint or IPublicKey) : Public key (only needed for a public-only object)
If priv_key is not None, it'll be discarded
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Bip32KeyNetVersions object
Raises:
Bip32KeyError: If the constructed key is not valid
"""
curve = self.Curve()
# Private key object
if priv_key is not None:
# Check that key type matches the Bip curve
if not isinstance(priv_key, bytes) and not isinstance(priv_key, curve.PrivateKeyClass()):
raise Bip32KeyError(f"Invalid private key class, a {curve.Name()} key is required")
self.m_priv_key = Bip32PrivateKey.FromBytesOrKeyObject(priv_key,
key_data,
key_net_ver,
self.CurveType())
self.m_pub_key = self.m_priv_key.PublicKey()
# Public-only object
else:
# Check that key type matches the Bip curve
if (not isinstance(pub_key, bytes)
and not isinstance(pub_key, curve.PointClass())
and not isinstance(pub_key, curve.PublicKeyClass())):
raise Bip32KeyError(f"Invalid public key class, a {curve.Name()} key or point is required")
self.m_priv_key = None
self.m_pub_key = Bip32PublicKey.FromBytesOrKeyObject(pub_key,
key_data,
key_net_ver,
self.CurveType())
def ChildKey(self,
index: Union[int, Bip32KeyIndex]) -> Bip32Base:
"""
Create and return a child key of the current one with the specified index.
The index shall be hardened using HardenIndex method to use the private derivation algorithm.
Args:
index (int or Bip32KeyIndex object): Index
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
"""
index = self.__GetIndex(index)
return self.__ValidateAndCkdPriv(index) if not self.IsPublicOnly() else self.__ValidateAndCkdPub(index)
def DerivePath(self,
path: Union[str, Bip32Path]) -> Bip32Base:
"""
Derive children keys from the specified path.
Args:
path (str or Bip32Path object): Path
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
Bip32PathError: If the path is not valid
ValueError: If the path is a master path and the key is a child key
"""
path = self.__GetPath(path)
if self.Depth() > 0 and path.IsAbsolute():
raise ValueError("Absolute paths can only be derived from a master key, not child ones")
bip32_obj = self
# Derive children keys
for path_elem in path:
bip32_obj = bip32_obj.ChildKey(path_elem)
return bip32_obj
def ConvertToPublic(self) -> None:
"""Convert the object into a public one."""
self.m_priv_key = None
def IsPublicOnly(self) -> bool:
"""
Get if it's public-only.
Returns:
bool: True if public-only, false otherwise
"""
return self.m_priv_key is None
def PrivateKey(self) -> Bip32PrivateKey:
"""
Return private key object.
Returns:
Bip32PrivateKey object: Bip32PrivateKey object
Raises:
Bip32KeyError: If internal key is public-only
"""
if self.IsPublicOnly():
raise Bip32KeyError("Public-only deterministic keys have no private half")
assert isinstance(self.m_priv_key, Bip32PrivateKey)
return self.m_priv_key
def PublicKey(self) -> Bip32PublicKey:
"""
Return public key object.
Returns:
Bip32PublicKey object: Bip32PublicKey object
"""
return self.m_pub_key
def KeyNetVersions(self) -> Bip32KeyNetVersions:
"""
Get key net versions.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return self.m_pub_key.KeyNetVersions()
def Depth(self) -> Bip32Depth:
"""
Get current depth.
Returns:
Bip32Depth object: Current depth
"""
return self.m_pub_key.Data().Depth()
def Index(self) -> Bip32KeyIndex:
"""
Get current index.
Returns:
Bip32KeyIndex object: Current index
"""
return self.m_pub_key.Data().Index()
def ChainCode(self) -> Bip32ChainCode:
"""
Get chain code.
Returns:
Bip32ChainCode: Chain code
"""
return self.m_pub_key.ChainCode()
def FingerPrint(self) -> Bip32FingerPrint:
"""
Get public key fingerprint.
Returns:
Bip32FingerPrint object: Public key fingerprint bytes
"""
return self.m_pub_key.FingerPrint()
def ParentFingerPrint(self) -> Bip32FingerPrint:
"""
Get parent fingerprint.
Returns:
Bip32FingerPrint object: Parent fingerprint bytes
"""
return self.m_pub_key.Data().ParentFingerPrint()
@classmethod
def Curve(cls) -> EllipticCurve:
"""
Return the elliptic curve.
Returns:
EllipticCurve object: EllipticCurve object
"""
return EllipticCurveGetter.FromType(cls.CurveType())
@classmethod
def IsPublicDerivationSupported(cls) -> bool:
"""
Get if public derivation is supported.
Returns:
bool: True if supported, false otherwise.
"""
return cls._KeyDerivator().IsPublicDerivationSupported()
#
# Private methods
#
def __ValidateAndCkdPriv(self,
index: Bip32KeyIndex) -> Bip32Base:
"""
Check the key index validity and create a child key with the specified index using private derivation.
Args:
index (Bip32KeyIndex object): Key index
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
"""
return self.__CkdPriv(index)
def __ValidateAndCkdPub(self,
index: Bip32KeyIndex) -> Bip32Base:
"""
Check the key index validity and create a child key with the specified index using public derivation.
Args:
index (Bip32KeyIndex object): Key index
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
"""
# Hardened index is not supported for public derivation
if index.IsHardened():
raise Bip32KeyError("Public child derivation cannot be used to create a hardened child key")
return self.__CkdPub(index)
def __CkdPriv(self,
index: Bip32KeyIndex) -> Bip32Base:
"""
Derive a child key with the specified index using private derivation.
Args:
index (Bip32KeyIndex object): Key index
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
"""
assert self.m_priv_key is not None
priv_key_bytes, chain_code_bytes = self._KeyDerivator().CkdPriv(self.m_priv_key,
self.m_pub_key,
index)
return self.__class__(
priv_key=priv_key_bytes,
pub_key=None,
key_data=Bip32KeyData(
chain_code=chain_code_bytes,
depth=self.Depth().Increase(),
index=index,
parent_fprint=self.FingerPrint()
),
key_net_ver=self.KeyNetVersions()
)
def __CkdPub(self,
index: Bip32KeyIndex) -> Bip32Base:
"""
Derive a child key with the specified index using public derivation.
Args:
index (Bip32KeyIndex object): Key index
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
"""
pub_key_bytes, chain_code_bytes = self._KeyDerivator().CkdPub(self.m_pub_key,
index)
return self.__class__(
priv_key=None,
pub_key=pub_key_bytes,
key_data=Bip32KeyData(
chain_code=chain_code_bytes,
depth=self.Depth().Increase(),
index=index,
parent_fprint=self.FingerPrint()
),
key_net_ver=self.KeyNetVersions()
)
@staticmethod
def __GetIndex(index: Union[int, Bip32KeyIndex]) -> Bip32KeyIndex:
"""
Get index object.
Args:
index (int or Bip32KeyIndex): Index
Returns:
Bip32KeyIndex object: Bip32KeyIndex object
"""
return Bip32KeyIndex(index) if isinstance(index, int) else index
@staticmethod
def __GetPath(path: Union[str, Bip32Path]) -> Bip32Path:
"""
Get path object.
Args:
path (str or Bip32Path): Path
Returns:
Bip32Path object: Bip32Path object
"""
return Bip32PathParser.Parse(path) if isinstance(path, str) else path
#
# Abstract methods
#
@staticmethod
@abstractmethod
def CurveType() -> EllipticCurveTypes:
"""
Return the elliptic curve type.
Returns:
EllipticCurveTypes: Curve type
"""
@staticmethod
@abstractmethod
def _DefaultKeyNetVersion() -> Bip32KeyNetVersions:
"""
Return the default key net version.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
@staticmethod
@abstractmethod
def _KeyDerivator() -> Type[IBip32KeyDerivator]:
"""
Return the key derivator class.
Returns:
IBip32KeyDerivator class: Key derivator class
"""
@staticmethod
@abstractmethod
def _MasterKeyGenerator() -> Type[IBip32MstKeyGenerator]:
"""
Return the master key generator class.
Returns:
IBip32MstKeyGenerator class: Master key generator class
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/base/bip32_base.py",
"license": "MIT License",
"lines": 471,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/base/ibip32_key_derivator.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 SLIP-0010 keys derivation."""
# Imports
from abc import ABC, abstractmethod
from typing import Tuple, Union
from ..bip32_key_data import Bip32KeyIndex
from ..bip32_keys import Bip32PrivateKey, Bip32PublicKey
from ...ecc import IPoint
class IBip32KeyDerivator(ABC):
"""Interface for generic BIP32 key derivator."""
@staticmethod
@abstractmethod
def IsPublicDerivationSupported() -> bool:
"""
Get if public derivation is supported.
Returns:
bool: True if supported, false otherwise.
"""
@classmethod
@abstractmethod
def CkdPriv(cls,
priv_key: Bip32PrivateKey,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[bytes, bytes]:
"""
Derive a child key with the specified index using private derivation.
Args:
priv_key (Bip32PrivateKey object): Bip32PrivateKey object
pub_key (Bip32PublicKey object) : Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
@classmethod
@abstractmethod
def CkdPub(cls,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[Union[bytes, IPoint], bytes]:
"""
Derive a child key with the specified index using public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes or IPoint, bytes]: Public key bytes or point (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/base/ibip32_key_derivator.py",
"license": "MIT License",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/base/ibip32_mst_key_generator.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 SLIP-0010 keys derivation."""
# Imports
from abc import ABC, abstractmethod
from typing import Tuple
class IBip32MstKeyGenerator(ABC):
"""Interface for generic BIP32 master key generator."""
@classmethod
@abstractmethod
def GenerateFromSeed(cls,
seed_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed.
Args:
seed_bytes (bytes): Seed bytes
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/base/ibip32_mst_key_generator.py",
"license": "MIT License",
"lines": 39,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_const.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with BIP32 constants."""
# Imports
from .bip32_key_net_ver import Bip32KeyNetVersions
class Bip32Const:
"""Class container for BIP32 constants."""
# Main net key net version (xpub / xprv)
MAIN_NET_KEY_NET_VERSIONS: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x88\xb2\x1e", b"\x04\x88\xad\xe4")
# Test net key net version (tpub / tprv)
TEST_NET_KEY_NET_VERSIONS: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x35\x87\xcf", b"\x04\x35\x83\x94")
# Key net version for BIP32 Kholaw that uses 64-byte private keys (xpub / xprv)
# KHOLAW_KEY_NET_VERSIONS: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x88\xb2\x1e", b"\x0f\x43\x31\xd4")
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_const.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_ex.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with BIP32 exceptions."""
class Bip32KeyError(Exception):
"""Exception in case of key error."""
class Bip32PathError(Exception):
"""Exception in case of path error."""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_ex.py",
"license": "MIT License",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_key_data.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper classes for BIP32 key data."""
# Imports
from __future__ import annotations
from typing import Union
from ..utils.misc import BitUtils, BytesUtils, DataBytes, IntegerUtils
from ..utils.typing import Literal
class Bip32KeyDataConst:
"""Class container for BIP32 key data constants."""
# Chaincode length in bytes
CHAINCODE_BYTE_LEN: int = 32
# Depth length in bytes
DEPTH_BYTE_LEN: int = 1
# Fingerprint length in bytes
FINGERPRINT_BYTE_LEN: int = 4
# Fingerprint of master key
FINGERPRINT_MASTER_KEY: bytes = b"\x00\x00\x00\x00"
# Key index length in bytes
KEY_INDEX_BYTE_LEN: int = 4
# Key index maximum value
KEY_INDEX_MAX_VAL: int = 2**32 - 1
# Key index hardened bit number
KEY_INDEX_HARDENED_BIT_NUM: int = 31
class Bip32ChainCode(DataBytes):
"""
BIP32 chaincode class.
It represents a BIP32 chaincode.
"""
def __init__(self,
chaincode: bytes = b"\x00" * Bip32KeyDataConst.CHAINCODE_BYTE_LEN) -> None:
"""
Construct class.
Args:
chaincode (bytes, optional): Fingerprint bytes (default: zero)
Raises:
ValueError: If the chain code length is not valid
"""
if len(chaincode) != self.FixedLength():
raise ValueError(f"Invalid chaincode length ({len(chaincode)})")
super().__init__(chaincode)
@staticmethod
def FixedLength() -> int:
"""
Get the fixed length in bytes.
Returns:
int: Length in bytes
"""
return Bip32KeyDataConst.CHAINCODE_BYTE_LEN
class Bip32FingerPrint(DataBytes):
"""
BIP32 fingerprint class.
It represents a BIP32 fingerprint.
"""
def __init__(self,
fprint: bytes = Bip32KeyDataConst.FINGERPRINT_MASTER_KEY) -> None:
"""
Construct class.
Args:
fprint (bytes, optional): Fingerprint bytes (default: master key)
Raises:
ValueError: If the chain code length is not valid
"""
if len(fprint) < self.FixedLength():
raise ValueError(f"Invalid fingerprint length ({len(fprint)})")
super().__init__(fprint[:Bip32KeyDataConst.FINGERPRINT_BYTE_LEN])
@staticmethod
def FixedLength() -> int:
"""
Get the fixed length in bytes.
Returns:
int: Length in bytes
"""
return Bip32KeyDataConst.FINGERPRINT_BYTE_LEN
def IsMasterKey(self) -> bool:
"""
Get if the fingerprint corresponds to a master key.
Returns:
bool: True if it corresponds to a master key, false otherwise
"""
return self.ToBytes() == Bip32KeyDataConst.FINGERPRINT_MASTER_KEY
class Bip32Depth:
"""
BIP32 depth class.
It represents a BIP32 depth.
"""
m_depth: int
def __init__(self,
depth: int) -> None:
"""
Construct class.
Args:
depth (int): Depth
Raises:
ValueError: If the depth value is not valid
"""
if depth < 0:
raise ValueError(f"Invalid depth ({depth})")
self.m_depth = depth
@staticmethod
def FixedLength() -> int:
"""
Get the fixed length in bytes.
Returns:
int: Length in bytes
"""
return Bip32KeyDataConst.DEPTH_BYTE_LEN
def Increase(self) -> Bip32Depth:
"""
Get a new object with increased depth.
Returns:
Bip32Depth object: Bip32Depth object
"""
return Bip32Depth(self.m_depth + 1)
def ToBytes(self) -> bytes:
"""
Get the depth as bytes.
Returns:
bytes: Depth bytes
"""
return IntegerUtils.ToBytes(self.m_depth, bytes_num=self.FixedLength())
def ToInt(self) -> int:
"""
Get the depth as integer.
Returns:
int: Depth index
"""
return int(self.m_depth)
def __int__(self) -> int:
"""
Get the depth as integer.
Returns:
int: Depth index
"""
return self.ToInt()
def __bytes__(self) -> bytes:
"""
Get the depth as bytes.
Returns:
bytes: Depth bytes
"""
return self.ToBytes()
def __eq__(self,
other: object) -> bool:
"""
Equality operator.
Args:
other (int or Bip32Depth object): Other object to compare
Returns:
bool: True if equal false otherwise
Raises:
TypeError: If the other object is not of the correct type
"""
if not isinstance(other, (int, Bip32Depth)):
raise TypeError(f"Invalid type for checking equality ({type(other)})")
if isinstance(other, int):
return self.m_depth == other
return self.m_depth == other.m_depth
def __gt__(self,
other: Union[int, Bip32Depth]) -> bool:
"""
Greater than operator.
Args:
other (int or Bip32Depth object): Other value to compare
Returns:
bool: True if greater false otherwise
"""
if isinstance(other, int):
return self.m_depth > other
return self.m_depth > other.m_depth
def __lt__(self,
other: Union[int, Bip32Depth]) -> bool:
"""
Lower than operator.
Args:
other (int or Bip32Depth object): Other value to compare
Returns:
bool: True if lower false otherwise
"""
if isinstance(other, int):
return self.m_depth < other
return self.m_depth < other.m_depth
class Bip32KeyIndex:
"""
BIP32 key index class.
It represents a BIP32 key index.
"""
m_idx: int
@staticmethod
def HardenIndex(index: int) -> int:
"""
Harden the specified index and return it.
Args:
index (int): Index
Returns:
int: Hardened index
"""
return BitUtils.SetBit(index, Bip32KeyDataConst.KEY_INDEX_HARDENED_BIT_NUM)
@staticmethod
def UnhardenIndex(index: int) -> int:
"""
Unharden the specified index and return it.
Args:
index (int): Index
Returns:
int: Unhardened index
"""
return BitUtils.ResetBit(index, Bip32KeyDataConst.KEY_INDEX_HARDENED_BIT_NUM)
@staticmethod
def IsHardenedIndex(index: int) -> bool:
"""
Get if the specified index is hardened.
Args:
index (int): Index
Returns:
bool: True if hardened, false otherwise
"""
return BitUtils.IsBitSet(index, Bip32KeyDataConst.KEY_INDEX_HARDENED_BIT_NUM)
@classmethod
def FromBytes(cls,
index_bytes: bytes) -> Bip32KeyIndex:
"""
Construct class from bytes.
Args:
index_bytes (bytes): Key index bytes
Returns:
Bip32KeyIndex object: Bip32KeyIndex object
Raises:
ValueError: If the index is not valid
"""
return cls(BytesUtils.ToInteger(index_bytes))
def __init__(self,
idx: int) -> None:
"""
Construct class.
Args:
idx (int): Key index
Raises:
ValueError: If the index value is not valid
"""
if idx < 0 or idx > Bip32KeyDataConst.KEY_INDEX_MAX_VAL:
raise ValueError(f"Invalid key index ({idx})")
self.m_idx = idx
@staticmethod
def FixedLength() -> int:
"""
Get the fixed length in bytes.
Returns:
int: Length in bytes
"""
return Bip32KeyDataConst.KEY_INDEX_BYTE_LEN
def Harden(self) -> Bip32KeyIndex:
"""
Get a new Bip32KeyIndex object with the current key index hardened.
Returns:
Bip32KeyIndex object: Bip32KeyIndex object
"""
return Bip32KeyIndex(self.HardenIndex(self.m_idx))
def Unharden(self) -> Bip32KeyIndex:
"""
Get a new Bip32KeyIndex object with the current key index unhardened.
Returns:
Bip32KeyIndex object: Bip32KeyIndex object
"""
return Bip32KeyIndex(self.UnhardenIndex(self.m_idx))
def IsHardened(self) -> bool:
"""
Get if the key index is hardened.
Returns:
bool: True if hardened, false otherwise
"""
return self.IsHardenedIndex(self.m_idx)
def ToBytes(self,
endianness: Literal["little", "big"] = "big") -> bytes:
"""
Get the key index as bytes.
Args:
endianness ("big" or "little", optional): Endianness (default: big)
Returns:
bytes: Key bytes
"""
return IntegerUtils.ToBytes(self.m_idx,
bytes_num=self.FixedLength(),
endianness=endianness)
def ToInt(self) -> int:
"""
Get the key index as integer.
Returns:
int: Key index
"""
return int(self.m_idx)
def __int__(self) -> int:
"""
Get the key index as integer.
Returns:
int: Key index
"""
return self.ToInt()
def __bytes__(self) -> bytes:
"""
Get the key index as bytes.
Returns:
bytes: Key bytes
"""
return self.ToBytes()
def __eq__(self,
other: object) -> bool:
"""
Equality operator.
Args:
other (int or Bip32KeyIndex object): Other value to compare
Returns:
bool: True if equal false otherwise
Raises:
TypeError: If the object is not of the correct type
"""
if not isinstance(other, (int, Bip32KeyIndex)):
raise TypeError(f"Invalid type for checking equality ({type(other)})")
if isinstance(other, int):
return self.m_idx == other
return self.m_idx == other.m_idx
class Bip32KeyData:
"""
BIP32 key data class.
It contains all additional data related to a BIP32 key (e.g. depth, chain code, etc...).
"""
m_depth: Bip32Depth
m_index: Bip32KeyIndex
m_chain_code: Bip32ChainCode
m_parent_fprint: Bip32FingerPrint
def __init__(self,
depth: Union[int, Bip32Depth] = Bip32Depth(0),
index: Union[int, Bip32KeyIndex] = Bip32KeyIndex(0),
chain_code: Union[bytes, Bip32ChainCode] = Bip32ChainCode(),
parent_fprint: Union[bytes, Bip32FingerPrint] = Bip32FingerPrint()) -> None:
"""
Construct class.
Args:
depth (Bip32Depth object) : Key depth
index (Bip32KeyIndex object) : Key index
chain_code (Bip32ChainCode object) : Key chain code
parent_fprint (Bip32FingerPrint object) : Key parent fingerprint
"""
self.m_depth = depth if isinstance(depth, Bip32Depth) else Bip32Depth(depth)
self.m_index = index if isinstance(index, Bip32KeyIndex) else Bip32KeyIndex(index)
self.m_chain_code = chain_code if isinstance(chain_code, Bip32ChainCode) else Bip32ChainCode(chain_code)
self.m_parent_fprint = (parent_fprint
if isinstance(parent_fprint, Bip32FingerPrint)
else Bip32FingerPrint(parent_fprint))
def Depth(self) -> Bip32Depth:
"""
Get current depth.
Returns:
Bip32Depth object: Current depth
"""
return self.m_depth
def Index(self) -> Bip32KeyIndex:
"""
Get current index.
Returns:
Bip32KeyIndex object: Current index
"""
return self.m_index
def ChainCode(self) -> Bip32ChainCode:
"""
Get current chain code.
Returns:
Bip32ChainCode object: Chain code
"""
return self.m_chain_code
def ParentFingerPrint(self) -> Bip32FingerPrint:
"""
Get parent fingerprint.
Returns:
Bip32FingerPrint object: Parent fingerprint
"""
return self.m_parent_fprint
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_key_data.py",
"license": "MIT License",
"lines": 394,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_key_net_ver.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 net version class."""
class Bip32KeyNetVersionsConst:
"""Class container for BIP32 key net versions constants."""
# Key net version length in bytes
KEY_NET_VERSION_BYTE_LEN: int = 4
class Bip32KeyNetVersions:
"""
BIP32 key net versions class.
It represents a BIP32 key net versions.
"""
m_pub_net_ver: bytes
m_priv_net_ver: bytes
def __init__(self,
pub_net_ver: bytes,
priv_net_ver: bytes) -> None:
"""
Construct class.
Args:
pub_net_ver (bytes) : Public net version
priv_net_ver (bytes): Private net version
"""
if (len(pub_net_ver) != self.Length()
or len(priv_net_ver) != self.Length()):
raise ValueError("Invalid key net version length")
self.m_pub_net_ver = pub_net_ver
self.m_priv_net_ver = priv_net_ver
@staticmethod
def Length() -> int:
"""
Get the key net version length.
Returns:
int: Key net version length
"""
return Bip32KeyNetVersionsConst.KEY_NET_VERSION_BYTE_LEN
def Public(self) -> bytes:
"""
Get public net version.
Returns:
bytes: Public net version
"""
return self.m_pub_net_ver
def Private(self) -> bytes:
"""
Get private net version.
Returns:
bytes: Private net version
"""
return self.m_priv_net_ver
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_key_net_ver.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_key_ser.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 extended key serialization/deserialization."""
# Imports
from typing import Tuple
from ..base58 import Base58Decoder, Base58Encoder
from .bip32_const import Bip32Const
from .bip32_ex import Bip32KeyError
from .bip32_key_data import Bip32ChainCode, Bip32Depth, Bip32FingerPrint, Bip32KeyData, Bip32KeyIndex
from .bip32_key_net_ver import Bip32KeyNetVersions
from ..ecc import IPrivateKey, IPublicKey
from ..utils.misc import BytesUtils
class Bip32KeySerConst:
"""Class container for BIP32 key serialize constants."""
# Serialized public key length in bytes
SERIALIZED_PUB_KEY_BYTE_LEN: int = 78
# Serialized private key length in bytes
SERIALIZED_PRIV_KEY_BYTE_LEN: Tuple[int, int] = (78, 110)
class _Bip32KeySerializer:
"""
BIP32 key serializer class.
It serializes private/public keys.
"""
@staticmethod
def Serialize(key_bytes: bytes,
key_data: Bip32KeyData,
key_net_ver_bytes: bytes) -> str:
"""
Serialize the specified key bytes.
Args:
key_bytes (bytes) : Key bytes
key_data (BipKeyData object): Key data
key_net_ver_bytes (bytes) : Key net version bytes
Returns:
str: Serialized key
"""
# Serialize key
ser_key = (
key_net_ver_bytes
+ bytes(key_data.Depth()) + bytes(key_data.ParentFingerPrint()) + bytes(key_data.Index())
+ bytes(key_data.ChainCode()) + key_bytes
)
# Encode it
return Base58Encoder.CheckEncode(ser_key)
class Bip32PrivateKeySerializer:
"""
BIP32 private key serializer class.
It serializes private keys.
"""
@staticmethod
def Serialize(priv_key: IPrivateKey,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS) -> str:
"""
Serialize a private key.
Args:
priv_key (IPrivateKey object) : IPrivateKey object
key_data (BipKeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object, optional): Key net versions (BIP32 main net version by default)
Returns:
str: Serialized private key
"""
return _Bip32KeySerializer.Serialize(b"\x00" + priv_key.Raw().ToBytes(),
key_data,
key_net_ver.Private())
class Bip32PublicKeySerializer:
"""
BIP32 public key serializer class.
It serializes public keys.
"""
@staticmethod
def Serialize(pub_key: IPublicKey,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS) -> str:
"""
Serialize a public key.
Args:
pub_key (IPublicKey object) : IPublicKey object
key_data (BipKeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object, optional): Key net versions (BIP32 main net version by default)
Returns:
str: Serialized public key
"""
return _Bip32KeySerializer.Serialize(pub_key.RawCompressed().ToBytes(),
key_data,
key_net_ver.Public())
class Bip32DeserializedKey:
"""
BIP32 deserialized key class.
It represents a key deserialized with the Bip32KeyDeserializer.
"""
m_key_bytes: bytes
m_key_data: Bip32KeyData
m_is_public: bool
def __init__(self,
key_bytes: bytes,
key_data: Bip32KeyData,
is_public: bool) -> None:
"""
Construct class.
Args:
key_bytes (bytes) : Key bytes
key_data (BipKeyData object): Key data
is_public (bool) : True if the key is public, false otherwise
Returns:
str: Serialized public key
"""
self.m_key_bytes = key_bytes
self.m_key_data = key_data
self.m_is_public = is_public
def KeyBytes(self) -> bytes:
"""
Get key bytes.
Returns:
bytes: Key bytes
"""
return self.m_key_bytes
def KeyData(self) -> Bip32KeyData:
"""
Get key data.
Returns:
Bip32KeyData object: Bip32KeyData object
"""
return self.m_key_data
def IsPublic(self) -> bool:
"""
Get if public.
Returns:
bool: True if the key is public, false otherwise
"""
return self.m_is_public
class Bip32KeyDeserializer:
"""
BIP32 key deserializer class.
It deserializes an extended key.
"""
@classmethod
def DeserializeKey(cls,
ser_key_str: str,
key_net_ver: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS) -> Bip32DeserializedKey:
"""
Deserialize a key.
Args:
ser_key_str (str) : Serialized key string
key_net_ver (Bip32KeyNetVersions object, optional): Key net versions (BIP32 main net version by default)
Returns:
Bip32DeserializedKey object: Bip32DeserializedKey object
Raises:
Bip32KeyError: If the key is not valid
"""
# Decode key
ser_key_bytes = Base58Decoder.CheckDecode(ser_key_str)
# Get if key is public/private depending on the net version
is_public = cls.__GetIfPublic(ser_key_bytes, key_net_ver)
# Validate length
if is_public and len(ser_key_bytes) != Bip32KeySerConst.SERIALIZED_PUB_KEY_BYTE_LEN:
raise Bip32KeyError(f"Invalid extended public key (wrong length: {len(ser_key_bytes)})")
if not is_public and len(ser_key_bytes) not in Bip32KeySerConst.SERIALIZED_PRIV_KEY_BYTE_LEN:
raise Bip32KeyError(f"Invalid extended private key (wrong length: {len(ser_key_bytes)})")
# Get parts back
key_bytes, key_data = cls.__GetPartsFromBytes(ser_key_bytes, is_public)
return Bip32DeserializedKey(key_bytes, key_data, is_public)
@staticmethod
def __GetIfPublic(ser_key_bytes: bytes,
key_net_ver: Bip32KeyNetVersions) -> bool:
"""
Get if the key is public.
Args:
ser_key_bytes (bytes) : Serialized key bytes
key_net_ver (Bip32KeyNetVersions object): Key net versions
Returns:
bool: True if public, false otherwise
Raises:
Bip32KeyError: If the key net version is not valid
"""
key_net_ver_got = ser_key_bytes[:Bip32KeyNetVersions.Length()]
if key_net_ver_got == key_net_ver.Public():
is_public = True
elif key_net_ver_got == key_net_ver.Private():
is_public = False
else:
raise Bip32KeyError(
f"Invalid extended key (wrong net version: {BytesUtils.ToHexString(key_net_ver_got)})"
)
return is_public
@staticmethod
def __GetPartsFromBytes(ser_key_bytes: bytes,
is_public: bool) -> Tuple[bytes, Bip32KeyData]:
"""
Get back key parts from serialized key bytes.
Args:
ser_key_bytes (bytes): Serialized key bytes
is_public (bool) : True if the key is public, false otherwise
Returns:
tuple[bytes, Bip32KeyData]: key bytes (index 0) and key data (index 1)
Raises:
Bip32KeyError: If the private key first byte is not zero
"""
# Compute indexes
depth_idx = Bip32KeyNetVersions.Length()
fprint_idx = depth_idx + Bip32Depth.FixedLength()
key_index_idx = fprint_idx + Bip32FingerPrint.FixedLength()
chain_code_idx = key_index_idx + Bip32KeyIndex.FixedLength()
key_idx = chain_code_idx + Bip32ChainCode.FixedLength()
# Get parts
depth = ser_key_bytes[depth_idx]
fprint_bytes = ser_key_bytes[fprint_idx:key_index_idx]
key_index_bytes = ser_key_bytes[key_index_idx:chain_code_idx]
chain_code_bytes = ser_key_bytes[chain_code_idx:key_idx]
key_bytes = ser_key_bytes[key_idx:]
key_data = Bip32KeyData(Bip32Depth(depth),
Bip32KeyIndex.FromBytes(key_index_bytes),
Bip32ChainCode(chain_code_bytes),
Bip32FingerPrint(fprint_bytes))
# If private key, the first byte shall be zero and shall be removed
if not is_public:
if key_bytes[0] != 0:
raise Bip32KeyError(f"Invalid extended private key (wrong secret: {key_bytes[0]})")
key_bytes = key_bytes[1:]
return key_bytes, key_data
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_key_ser.py",
"license": "MIT License",
"lines": 237,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_keys.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 keys handling."""
# Imports
from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import Union
from .bip32_ex import Bip32KeyError
from .bip32_key_data import Bip32ChainCode, Bip32FingerPrint, Bip32KeyData
from .bip32_key_net_ver import Bip32KeyNetVersions
from .bip32_key_ser import Bip32PrivateKeySerializer, Bip32PublicKeySerializer
from ..ecc import EllipticCurve, EllipticCurveGetter, EllipticCurveTypes, IPoint, IPrivateKey, IPublicKey
from ..utils.crypto import Hash160
from ..utils.misc import DataBytes
class _Bip32KeyBase(ABC):
"""Base class for a generic BIP32 key."""
m_curve: EllipticCurve
m_curve_type: EllipticCurveTypes
m_key_data: Bip32KeyData
m_key_net_ver: Bip32KeyNetVersions
def __init__(self,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions,
curve_type: EllipticCurveTypes) -> None:
"""
Construct class.
Args:
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
curve_type (EllipticCurveTypes) : Elliptic curve type
"""
self.m_curve = EllipticCurveGetter.FromType(curve_type)
self.m_curve_type = curve_type
self.m_key_data = key_data
self.m_key_net_ver = key_net_ver
def Curve(self) -> EllipticCurve:
"""
Return key elliptic curve.
Returns:
EllipticCurve object: EllipticCurve object
"""
return self.m_curve
def CurveType(self) -> EllipticCurveTypes:
"""
Return key elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
return self.m_curve_type
def Data(self) -> Bip32KeyData:
"""
Return key data.
Returns:
BipKeyData object: BipKeyData object
"""
return self.m_key_data
def ChainCode(self) -> Bip32ChainCode:
"""
Return the chain code.
Returns:
Bip32ChainCode object: Bip32ChainCode object
"""
return self.Data().ChainCode()
def KeyNetVersions(self) -> Bip32KeyNetVersions:
"""
Get key net versions.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return self.m_key_net_ver
@abstractmethod
def ToExtended(self) -> str:
"""
Return key in serialized extended format.
Returns:
str: Key in serialized extended format
"""
class Bip32PublicKey(_Bip32KeyBase):
"""
BIP32 public key class.
It represents a public key used by BIP32 with all the related data (e.g. depth, chain code, etc...).
"""
m_pub_key: IPublicKey
@classmethod
def FromBytesOrKeyObject(cls,
pub_key: Union[bytes, IPoint, IPublicKey],
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions,
curve_type: EllipticCurveTypes) -> Bip32PublicKey:
"""
Get the public key from key bytes or object.
Args:
pub_key (bytes, IPoint or IPublicKey) : Public key
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
curve_type (EllipticCurveTypes) : Elliptic curve type
Returns:
Bip32PublicKey object: Bip32PublicKey object
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
if isinstance(pub_key, bytes):
return cls.FromBytes(pub_key, key_data, key_net_ver, curve_type)
if isinstance(pub_key, IPoint):
return cls.FromPoint(pub_key, key_data, key_net_ver)
return cls(pub_key, key_data, key_net_ver)
@classmethod
def FromBytes(cls,
key_bytes: bytes,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions,
curve_type: EllipticCurveTypes) -> Bip32PublicKey:
"""
Create from bytes.
Args:
key_bytes (bytes) : Key bytes
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
curve_type (EllipticCurveTypes) : Elliptic curve type
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
return cls(cls.__KeyFromBytes(key_bytes, curve_type),
key_data,
key_net_ver)
@classmethod
def FromPoint(cls,
key_point: IPoint,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions) -> Bip32PublicKey:
"""
Create from point.
Args:
key_point (IPoint object) : Key point
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
return cls(cls.__KeyFromPoint(key_point),
key_data,
key_net_ver)
def __init__(self,
pub_key: IPublicKey,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions) -> None:
"""
Construct class.
Args:
pub_key (IPublicKey object) : Key object
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
"""
super().__init__(key_data, key_net_ver, pub_key.CurveType())
self.m_pub_key = pub_key
def KeyObject(self) -> IPublicKey:
"""
Return the key object.
Returns:
IPublicKey object: Key object
"""
return self.m_pub_key
@lru_cache()
def RawCompressed(self) -> DataBytes:
"""
Return raw compressed public key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_pub_key.RawCompressed()
@lru_cache()
def RawUncompressed(self) -> DataBytes:
"""
Return raw uncompressed public key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_pub_key.RawUncompressed()
def Point(self) -> IPoint:
"""
Get public key point.
Returns:
IPoint object: IPoint object
"""
return self.m_pub_key.Point()
@lru_cache()
def FingerPrint(self) -> Bip32FingerPrint:
"""
Get key fingerprint.
Returns:
bytes: Key fingerprint bytes
"""
return Bip32FingerPrint(self.KeyIdentifier())
@lru_cache()
def KeyIdentifier(self) -> bytes:
"""
Get key identifier.
Returns:
bytes: Key identifier bytes
"""
return Hash160.QuickDigest(self.m_pub_key.RawCompressed().ToBytes())
@lru_cache()
def ToExtended(self) -> str:
"""
Return key in serialized extended format.
Returns:
str: Key in serialized extended format
"""
return Bip32PublicKeySerializer.Serialize(self.m_pub_key,
self.m_key_data,
self.m_key_net_ver)
@staticmethod
def __KeyFromBytes(key_bytes: bytes,
curve_type: EllipticCurveTypes) -> IPublicKey:
"""
Construct key from bytes.
Args:
key_bytes (bytes) : Key bytes
curve_type (EllipticCurveTypes): Elliptic curve type
Returns:
IPublicKey object: IPublicKey object
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
try:
curve = EllipticCurveGetter.FromType(curve_type)
return curve.PublicKeyClass().FromBytes(key_bytes)
except ValueError as ex:
raise Bip32KeyError("Invalid public key bytes") from ex
@staticmethod
def __KeyFromPoint(key_point: IPoint) -> IPublicKey:
"""
Construct key from point.
Args:
key_point (IPoint object): Key point
Returns:
IPublicKey object: IPublicKey object
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
try:
curve = EllipticCurveGetter.FromType(key_point.CurveType())
return curve.PublicKeyClass().FromPoint(key_point)
except ValueError as ex:
raise Bip32KeyError("Invalid public key point") from ex
class Bip32PrivateKey(_Bip32KeyBase):
"""
BIP32 private key class.
It represents a private key used by BIP32 with all the related data (e.g. depth, chain code, etc...).
"""
m_priv_key: IPrivateKey
@classmethod
def FromBytesOrKeyObject(cls,
priv_key: Union[bytes, IPrivateKey],
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions,
curve_type: EllipticCurveTypes) -> Bip32PrivateKey:
"""
Get the public key from key bytes or object.
Args:
priv_key (bytes or IPrivateKey) : Private key
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
curve_type (EllipticCurveTypes) : Elliptic curve type
Returns:
Bip32PrivateKey object: Bip32PrivateKey object
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
return (cls.FromBytes(priv_key, key_data, key_net_ver, curve_type)
if isinstance(priv_key, bytes)
else cls(priv_key, key_data, key_net_ver))
@classmethod
def FromBytes(cls,
key_bytes: bytes,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions,
curve_type: EllipticCurveTypes) -> Bip32PrivateKey:
"""
Create from bytes.
Args:
key_bytes (bytes) : Key bytes
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
curve_type (EllipticCurveTypes) : Elliptic curve type
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
return cls(cls.__KeyFromBytes(key_bytes, curve_type),
key_data,
key_net_ver)
def __init__(self,
priv_key: IPrivateKey,
key_data: Bip32KeyData,
key_net_ver: Bip32KeyNetVersions) -> None:
"""
Construct class.
Args:
priv_key (IPrivateKey object) : Key object
key_data (Bip32KeyData object) : Key data
key_net_ver (Bip32KeyNetVersions object): Key net versions
"""
super().__init__(key_data, key_net_ver, priv_key.CurveType())
self.m_priv_key = priv_key
def KeyObject(self) -> IPrivateKey:
"""
Return the key object.
Returns:
IPrivateKey object: Key object
"""
return self.m_priv_key
@lru_cache()
def Raw(self) -> DataBytes:
"""
Return raw private key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_priv_key.Raw()
@lru_cache()
def PublicKey(self) -> Bip32PublicKey:
"""
Get the public key correspondent to the private one.
Returns:
Bip32PublicKey object: Bip32PublicKey object
"""
return Bip32PublicKey(self.m_priv_key.PublicKey(),
self.m_key_data,
self.m_key_net_ver)
@lru_cache()
def ToExtended(self) -> str:
"""
Return key in serialized extended format.
Returns:
str: Key in serialized extended format
"""
return Bip32PrivateKeySerializer.Serialize(self.m_priv_key,
self.m_key_data,
self.m_key_net_ver)
@staticmethod
def __KeyFromBytes(key_bytes: bytes,
curve_type: EllipticCurveTypes) -> IPrivateKey:
"""
Construct key from bytes.
Args:
key_bytes (bytes) : Key bytes
curve_type (EllipticCurveTypes): Elliptic curve type
Returns:
IPrivateKey object: IPrivateKey object
Raises:
Bip32KeyError: If the key constructed from the bytes is not valid
"""
try:
curve = EllipticCurveGetter.FromType(curve_type)
return curve.PrivateKeyClass().FromBytes(key_bytes)
except ValueError as ex:
raise Bip32KeyError("Invalid private key bytes") from ex
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_keys.py",
"license": "MIT License",
"lines": 375,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_path.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP32 paths parsing and handling."""
# Import
from __future__ import annotations
from typing import Iterator, List, Optional, Sequence, Tuple, Union
from .bip32_ex import Bip32PathError
from .bip32_key_data import Bip32KeyIndex
class Bip32PathConst:
"""Class container for BIP32 path constants."""
# Hardened characters
HARDENED_CHARS: Tuple[str, str, str] = ("'", "h", "p")
# Master character
MASTER_CHAR: str = "m"
class Bip32Path:
"""
BIP32 path class.
It represents a BIP-0032 path.
"""
m_elems: List[Bip32KeyIndex]
m_is_absolute: bool
def __init__(self,
elems: Optional[Sequence[Union[int, Bip32KeyIndex]]] = None,
is_absolute: bool = True) -> None:
"""
Construct class.
Args:
elems (list, optional) : Path elements (default: empty)
is_absolute (bool, optional): True if path is an absolute one, false otherwise (default: True)
"""
try:
self.m_elems = ([]
if elems is None
else [Bip32KeyIndex(elem) if isinstance(elem, int) else elem for elem in elems])
except ValueError as ex:
raise Bip32PathError("The path contains some invalid key indexes") from ex
self.m_is_absolute = is_absolute
def AddElem(self,
elem: Union[int, Bip32KeyIndex]) -> Bip32Path:
"""
Return a new path object with the specified element added.
Args:
elem (str or Bip32KeyIndex): Path element
Returns:
Bip32Path object: Bip32Path object
Raises:
Bip32PathError: If the path element is not valid
"""
if isinstance(elem, int):
elem = Bip32KeyIndex(elem)
return Bip32Path(self.m_elems + [elem], self.m_is_absolute)
def IsAbsolute(self) -> bool:
"""
Get if absolute path.
Returns:
bool: True if absolute path, false otherwise
"""
return self.m_is_absolute
def Length(self) -> int:
"""
Get the number of elements of the path.
Returns:
int: Number of elements
"""
return len(self.m_elems)
def ToList(self) -> List[int]:
"""
Get the path as a list of integers.
Returns:
list[int]: Path as a list of integers
"""
return [int(elem) for elem in self.m_elems]
def ToStr(self) -> str:
"""
Get the path as a string.
Returns:
str: Path as a string
"""
path_str = "" if not self.m_is_absolute else f"{Bip32PathConst.MASTER_CHAR}/"
for elem in self.m_elems:
if not elem.IsHardened():
path_str += f"{str(elem.ToInt())}/"
else:
path_str += f"{str(Bip32KeyIndex.UnhardenIndex(elem.ToInt()))}'/"
return path_str[:-1]
def __str__(self) -> str:
"""
Get the path as a string.
Returns:
str: Path as a string
"""
return self.ToStr()
def __getitem__(self,
idx: int) -> Bip32KeyIndex:
"""
Get the specified element index.
Args:
idx (int): Element index
Returns:
Bip32KeyIndex object: Bip32KeyIndex object
"""
return self.m_elems[idx]
def __iter__(self) -> Iterator[Bip32KeyIndex]:
"""
Get the iterator to the current element.
Returns:
Iterator object: Iterator to the current element
"""
yield from self.m_elems
class Bip32PathParser:
"""
BIP32 path parser class.
It parses a BIP-0032 path and returns a Bip32Path object.
"""
@staticmethod
def Parse(path: str) -> Bip32Path:
"""
Parse a path and return a Bip32Path object.
Args:
path (str): Path
Returns:
Bip32Path object: Bip32Path object
Raises:
Bip32PathError: If the path is not valid
"""
# Remove trailing "/" if any
if path.endswith("/"):
path = path[:-1]
# Parse elements
return Bip32PathParser.__ParseElements(
list(filter(None, path.split("/")))
)
@staticmethod
def __ParseElements(path_elems: List[str]) -> Bip32Path:
"""
Parse path elements and return a Bip32Path object.
Args:
path_elems (list[str]): Path elements
Returns:
Bip32Path object: Bip32Path object
Raises:
Bip32PathError: If the path is not valid
"""
# Remove the initial "m" character if any
if len(path_elems) > 0 and path_elems[0] == Bip32PathConst.MASTER_CHAR:
path_elems = path_elems[1:]
is_absolute = True
else:
is_absolute = False
# Parse elements
parsed_elems = list(map(Bip32PathParser.__ParseElem, path_elems))
return Bip32Path(parsed_elems, is_absolute)
@staticmethod
def __ParseElem(path_elem: str) -> int:
"""
Parse path element and get the correspondent index.
Args:
path_elem (str): Path element
Returns:
int: Index of the element, None if the element is not a valid index
Raises:
Bip32PathError: If the path is not valid
"""
# Strip spaces
path_elem = path_elem.strip()
# Get if hardened
is_hardened = path_elem.endswith(Bip32PathConst.HARDENED_CHARS)
# If hardened, remove the last character from the string
if is_hardened:
path_elem = path_elem[:-1]
# The remaining string shall be numeric
if not path_elem.isnumeric():
raise Bip32PathError(f"Invalid path element ({path_elem})")
return int(path_elem) if not is_hardened else Bip32KeyIndex.HardenIndex(int(path_elem))
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_path.py",
"license": "MIT License",
"lines": 191,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_utils.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with BIP32 utility functions."""
# Imports
from .bip32_key_data import Bip32KeyIndex
class Bip32Utils:
"""
BIP32 utility class.
It contains some helper methods for Bip32 indexes.
Deprecated: only for compatibility, methods were moved to Bip32KeyIndex.
"""
@staticmethod
def HardenIndex(index: int) -> int:
"""
Harden the specified index and return it.
Args:
index (int): Index
Returns:
int: Hardened index
"""
return Bip32KeyIndex.HardenIndex(index)
@staticmethod
def UnhardenIndex(index: int) -> int:
"""
Unharden the specified index and return it.
Args:
index (int): Index
Returns:
int: Unhardened index
"""
return Bip32KeyIndex.UnhardenIndex(index)
@staticmethod
def IsHardenedIndex(index: int) -> bool:
"""
Get if the specified index is hardened.
Args:
index (int): Index
Returns:
bool: True if hardened, false otherwise
"""
return Bip32KeyIndex.IsHardenedIndex(index)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_utils.py",
"license": "MIT License",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_ed25519.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for keys derivation based on ed25519 curve as defined by BIP32 Khovratovich/Law."""
# Imports
from typing import Type
from .base import Bip32Base, IBip32KeyDerivator, IBip32MstKeyGenerator
from .bip32_const import Bip32Const
from .bip32_key_net_ver import Bip32KeyNetVersions
from .kholaw.bip32_kholaw_ed25519_key_derivator import Bip32KholawEd25519KeyDerivator
from .kholaw.bip32_kholaw_mst_key_generator import Bip32KholawEd25519MstKeyGenerator
from bip_utils.ecc import EllipticCurveTypes
class Bip32KholawEd25519(Bip32Base):
"""
BIP32 Khovratovich/Law ed25519 class.
It allows master keys generation and keys derivation using ed25519 curve.
"""
@staticmethod
def CurveType() -> EllipticCurveTypes:
"""
Return the elliptic curve type.
Returns:
EllipticCurveTypes: Curve type
"""
return EllipticCurveTypes.ED25519_KHOLAW
@staticmethod
def _DefaultKeyNetVersion() -> Bip32KeyNetVersions:
"""
Return the default key net version.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return Bip32Const.KHOLAW_KEY_NET_VERSIONS
@staticmethod
def _KeyDerivator() -> Type[IBip32KeyDerivator]:
"""
Return the key derivator class.
Returns:
IBip32KeyDerivator class: Key derivator class
"""
return Bip32KholawEd25519KeyDerivator
@staticmethod
def _MasterKeyGenerator() -> Type[IBip32MstKeyGenerator]:
"""
Return the master key generator class.
Returns:
IBip32MstKeyGenerator class: Master key generator class
"""
return Bip32KholawEd25519MstKeyGenerator
# Deprecated: only for compatibility
Bip32Ed25519Kholaw = Bip32KholawEd25519
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_ed25519.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_ed25519_key_derivator.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP32 Khovratovich/Law keys derivation.
Reference: https://github.com/LedgerHQ/orakolo/blob/master/papers/Ed25519_BIP%20Final.pdf
"""
# Imports
from .bip32_ex import Bip32KeyError
from .bip32_key_data import Bip32KeyIndex
from .bip32_keys import Bip32PublicKey
from .kholaw.bip32_kholaw_key_derivator_base import Bip32KholawEd25519KeyDerivatorBase
from bip_utils.ecc import Ed25519KholawPrivateKey, EllipticCurve, IPoint
from ..utils.misc import BytesUtils, IntegerUtils
class Bip32KholawEd25519KeyDerivator(Bip32KholawEd25519KeyDerivatorBase):
"""
BIP32 Khovratovich/Law ed25519 key derivator class.
It allows keys derivation for ed25519 curves in according to BIP32 Khovratovich/Law.
"""
@staticmethod
def _SerializeIndex(index: Bip32KeyIndex) -> bytes:
"""
Serialize key index.
Args:
index (Bip32KeyIndex object): Key index
Returns:
bytes: Serialized index
"""
return index.ToBytes(endianness="little")
@staticmethod
def _NewPrivateKeyLeftPart(zl_bytes: bytes,
kl_bytes: bytes,
curve: EllipticCurve) -> bytes:
"""
Compute the new private key left part for private derivation.
Args:
zl_bytes (bytes) : Leftmost Z 32-byte
kl_bytes (bytes) : Leftmost private key 32-byte
curve (EllipticCurve object): EllipticCurve object
Returns:
bytes: Leftmost new private key 32-byte
"""
zl_int = BytesUtils.ToInteger(zl_bytes[:28], endianness="little")
kl_int = BytesUtils.ToInteger(kl_bytes, endianness="little")
prvl_int = (zl_int * 8) + kl_int
# Discard child if multiple of curve order
if prvl_int % curve.Order() == 0:
raise Bip32KeyError("Computed child key is not valid, very unlucky index")
return IntegerUtils.ToBytes(prvl_int,
bytes_num=Ed25519KholawPrivateKey.Length() // 2,
endianness="little")
@staticmethod
def _NewPrivateKeyRightPart(zr_bytes: bytes,
kr_bytes: bytes) -> bytes:
"""
Compute the new private key right part for private derivation.
Args:
zr_bytes (bytes): Rightmost Z 32-byte
kr_bytes (bytes): Rightmost private key 32-byte
Returns:
bytes: Rightmost new private key 32-byte
"""
zr_int = BytesUtils.ToInteger(zr_bytes, endianness="little")
kpr_int = BytesUtils.ToInteger(kr_bytes, endianness="little")
kr_int = (zr_int + kpr_int) % (2 ** 256)
return IntegerUtils.ToBytes(kr_int,
bytes_num=Ed25519KholawPrivateKey.Length() // 2,
endianness="little")
@staticmethod
def _NewPublicKeyPoint(pub_key: Bip32PublicKey,
zl_bytes: bytes) -> IPoint:
"""
Compute new public key point for public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
zl_bytes (bytes) : Leftmost Z 32-byte
Returns:
IPoint object: IPoint object
"""
# Compute the new public key point: PKEY + 8ZL * G
zl_int = BytesUtils.ToInteger(zl_bytes[:28], endianness="little")
return pub_key.Point() + ((zl_int * 8) * pub_key.Curve().Generator())
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_ed25519_key_derivator.py",
"license": "MIT License",
"lines": 98,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_key_derivator_base.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP32 Khovratovich/Law keys derivation (base).
Reference: https://github.com/LedgerHQ/orakolo/blob/master/papers/Ed25519_BIP%20Final.pdf
"""
# Imports
from abc import ABC, abstractmethod
from typing import Tuple, Union
from .base import IBip32KeyDerivator
from .bip32_ex import Bip32KeyError
from .bip32_key_data import Bip32KeyIndex
from .bip32_keys import Bip32PrivateKey, Bip32PublicKey
from bip_utils.ecc import EllipticCurve, IPoint
from ..utils.crypto import HmacSha512
class Bip32KholawEd25519KeyDerivatorBase(IBip32KeyDerivator, ABC):
"""
BIP32 Khovratovich/Law ed25519 key derivator base class.
It allows keys derivation for ed25519 curves in according to BIP32 Khovratovich/Law.
It shall be inherited by child classes to customize the derivation algorithm.
"""
@staticmethod
def IsPublicDerivationSupported() -> bool:
"""
Get if public derivation is supported.
Returns:
bool: True if supported, false otherwise.
"""
return True
@classmethod
def CkdPriv(cls,
priv_key: Bip32PrivateKey,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[bytes, bytes]:
"""
Derive a child key with the specified index using private derivation.
Args:
priv_key (Bip32PrivateKey object): Bip32PrivateKey object
pub_key (Bip32PublicKey object) : Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
# Get index and key bytes
index_bytes = cls._SerializeIndex(index)
chain_code_bytes = priv_key.ChainCode().ToBytes()
priv_key_bytes = priv_key.Raw().ToBytes()
pub_key_bytes = pub_key.RawCompressed().ToBytes()[1:]
# Compute Z and chain code
if index.IsHardened():
z_bytes = HmacSha512.QuickDigest(chain_code_bytes,
b"\x00" + priv_key_bytes + index_bytes)
chain_code_bytes = HmacSha512.QuickDigestHalves(chain_code_bytes,
b"\x01" + priv_key_bytes + index_bytes)[1]
else:
z_bytes = HmacSha512.QuickDigest(chain_code_bytes,
b"\x02" + pub_key_bytes + index_bytes)
chain_code_bytes = HmacSha512.QuickDigestHalves(chain_code_bytes,
b"\x03" + pub_key_bytes + index_bytes)[1]
# Compute the left and right part of the new private key
hmac_half_len = HmacSha512.DigestSize() // 2
kl_bytes = cls._NewPrivateKeyLeftPart(z_bytes[:hmac_half_len],
priv_key_bytes[:hmac_half_len],
pub_key.Curve())
kr_bytes = cls._NewPrivateKeyRightPart(z_bytes[hmac_half_len:],
priv_key_bytes[hmac_half_len:])
return kl_bytes + kr_bytes, chain_code_bytes
@classmethod
def CkdPub(cls,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[Union[bytes, IPoint], bytes]:
"""
Derive a child key with the specified index using public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes or IPoint, bytes]: Public key bytes or point (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
# Get index and key bytes
index_bytes = cls._SerializeIndex(index)
chain_code_bytes = pub_key.ChainCode().ToBytes()
pub_key_bytes = pub_key.RawCompressed().ToBytes()[1:]
# Compute Z and chain code
z_bytes = HmacSha512.QuickDigest(chain_code_bytes,
b"\x02" + pub_key_bytes + index_bytes)
chain_code_bytes = HmacSha512.QuickDigestHalves(chain_code_bytes,
b"\x03" + pub_key_bytes + index_bytes)[1]
# Compute the new public key point
hmac_half_len = HmacSha512.DigestSize() // 2
new_pub_key_point = cls._NewPublicKeyPoint(pub_key,
z_bytes[:hmac_half_len])
# If the public key is the identity point (0, 1) discard the child
if new_pub_key_point.X() == 0 and new_pub_key_point.Y() == 1:
raise Bip32KeyError("Computed public child key is not valid, very unlucky index")
return new_pub_key_point, chain_code_bytes
#
# Abstract methods
#
@staticmethod
@abstractmethod
def _SerializeIndex(index: Bip32KeyIndex) -> bytes:
"""
Serialize key index.
Args:
index (Bip32KeyIndex object): Key index
Returns:
bytes: Serialized index
"""
@staticmethod
@abstractmethod
def _NewPrivateKeyLeftPart(zl_bytes: bytes,
kl_bytes: bytes,
curve: EllipticCurve) -> bytes:
"""
Compute the new private key left part for private derivation.
Args:
zl_bytes (bytes) : Leftmost Z 32-byte
kl_bytes (bytes) : Leftmost private key 32-byte
curve (EllipticCurve object): EllipticCurve object
Returns:
bytes: Leftmost new private key 32-byte
"""
@staticmethod
@abstractmethod
def _NewPrivateKeyRightPart(zr_bytes: bytes,
kr_bytes: bytes) -> bytes:
"""
Compute the new private key right part for private derivation.
Args:
zr_bytes (bytes): Rightmost Z 32-byte
kr_bytes (bytes): Rightmost private key 32-byte
Returns:
bytes: Rightmost new private key 32-byte
"""
@staticmethod
@abstractmethod
def _NewPublicKeyPoint(pub_key: Bip32PublicKey,
zl_bytes: bytes) -> IPoint:
"""
Compute new public key point for public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
zl_bytes (bytes) : Leftmost Z 32-byte
Returns:
IPoint object: IPoint object
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_key_derivator_base.py",
"license": "MIT License",
"lines": 168,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_mst_key_generator.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP32 Khovratovich/Law master key generation.
Reference: https://github.com/LedgerHQ/orakolo/blob/master/papers/Ed25519_BIP%20Final.pdf
"""
# Imports
from typing import Tuple
from .base import IBip32MstKeyGenerator
from .slip10.bip32_slip10_mst_key_generator import Bip32Slip10MstKeyGeneratorConst
from ..utils.crypto import HmacSha256, HmacSha512
from ..utils.misc import BitUtils
class Bip32KholawMstKeyGeneratorConst:
"""Class container for BIP32 Khovratovich/Law master key generator constants."""
# Minimum length in bytes for seed
SEED_MIN_BYTE_LEN: int = Bip32Slip10MstKeyGeneratorConst.SEED_MIN_BYTE_LEN
# HMAC key for generating master key
MASTER_KEY_HMAC_KEY: bytes = Bip32Slip10MstKeyGeneratorConst.HMAC_KEY_ED25519_BYTES
class Bip32KholawEd25519MstKeyGenerator(IBip32MstKeyGenerator):
"""
BIP32 Khovratovich/Law ed25519 master key generator class.
It allows master keys generation in according to BIP32 Khovratovich/Law for ed25519 curve.
"""
@classmethod
def GenerateFromSeed(cls,
seed_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed.
Args:
seed_bytes (bytes): Seed bytes
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
if len(seed_bytes) < Bip32KholawMstKeyGeneratorConst.SEED_MIN_BYTE_LEN:
raise ValueError(f"Invalid seed length ({len(seed_bytes)})")
# Compute kL and kR
kl_bytes, kr_bytes = cls.__HashRepeatedly(seed_bytes, Bip32KholawMstKeyGeneratorConst.MASTER_KEY_HMAC_KEY)
# Tweak kL bytes
kl_bytes = cls.__TweakMasterKeyBits(kl_bytes)
# Compute chain code
chain_code_bytes = HmacSha256.QuickDigest(Bip32KholawMstKeyGeneratorConst.MASTER_KEY_HMAC_KEY,
b"\x01" + seed_bytes)
return kl_bytes + kr_bytes, chain_code_bytes
@classmethod
def __HashRepeatedly(cls,
data_bytes: bytes,
hmac_key_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Continue to hash the data bytes until the third-highest bit of the last byte is not zero.
Args:
data_bytes (bytes) : Data bytes
hmac_key_bytes (bytes): HMAC key bytes
Returns:
tuple[bytes, bytes]: Two halves of the computed hash
"""
kl_bytes, kr_bytes = HmacSha512.QuickDigestHalves(hmac_key_bytes,
data_bytes)
if BitUtils.AreBitsSet(kl_bytes[31], 0x20):
return cls.__HashRepeatedly(kl_bytes + kr_bytes, hmac_key_bytes)
return kl_bytes, kr_bytes
@staticmethod
def __TweakMasterKeyBits(key_bytes: bytes) -> bytes:
"""
Tweak master key bits.
Args:
key_bytes (bytes): Key bytes
Returns:
bytes: Tweaked key bytes
"""
key_bytes = bytearray(key_bytes)
# Clear the lowest 3 bits of the first byte of kL
key_bytes[0] = BitUtils.ResetBits(key_bytes[0], 0x07)
# Clear the highest bit of the last byte of kL
key_bytes[31] = BitUtils.ResetBits(key_bytes[31], 0x80)
# Set the second-highest bit of the last byte of kL
key_bytes[31] = BitUtils.SetBits(key_bytes[31], 0x40)
return bytes(key_bytes)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/kholaw/bip32_kholaw_mst_key_generator.py",
"license": "MIT License",
"lines": 97,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_key_derivator.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP32 SLIP-0010 keys derivation.
References:
https://github.com/satoshilabs/slips/blob/master/slip-0010.md
https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
"""
# Imports
from typing import Tuple, Union
from ..base import IBip32KeyDerivator
from ..bip32_ex import Bip32KeyError
from ..bip32_key_data import Bip32KeyIndex
from ..bip32_keys import Bip32PrivateKey, Bip32PublicKey
from ...ecc import IPoint
from ...utils.crypto import HmacSha512
from ...utils.misc import BytesUtils, IntegerUtils
class Bip32Slip10DerivatorConst:
"""Class container for BIP32 SLIP-0010 derivator constants."""
# Private key prefix
PRIV_KEY_PREFIX: bytes = b"\x00"
class Bip32Slip10EcdsaDerivator(IBip32KeyDerivator):
"""
BIP32 SLIP-0010 ECDSA key derivator class.
It allows keys derivation for ECDSA curves in according to BIP32 SLIP-0010.
"""
@staticmethod
def IsPublicDerivationSupported() -> bool:
"""
Get if public derivation is supported.
Returns:
bool: True if supported, false otherwise.
"""
return True
@classmethod
def CkdPriv(cls,
priv_key: Bip32PrivateKey,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[bytes, bytes]:
"""
Derive a child key with the specified index using private derivation.
Args:
priv_key (Bip32PrivateKey object): Bip32PrivateKey object
pub_key (Bip32PublicKey object) : Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
curve = pub_key.Curve()
priv_key_bytes = priv_key.Raw().ToBytes()
# Data for HMAC
if index.IsHardened():
data_bytes = (Bip32Slip10DerivatorConst.PRIV_KEY_PREFIX
+ priv_key_bytes
+ index.ToBytes())
else:
data_bytes = pub_key.RawCompressed().ToBytes() + index.ToBytes()
# Compute HMAC halves
il_bytes, ir_bytes = HmacSha512.QuickDigestHalves(priv_key.ChainCode().ToBytes(),
data_bytes)
# Construct new key secret from iL and current private key
il_int = BytesUtils.ToInteger(il_bytes)
priv_key_int = BytesUtils.ToInteger(priv_key_bytes)
new_priv_key_bytes = IntegerUtils.ToBytes((il_int + priv_key_int) % curve.Order(),
bytes_num=curve.PrivateKeyClass().Length())
return new_priv_key_bytes, ir_bytes
@classmethod
def CkdPub(cls,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[Union[bytes, IPoint], bytes]:
"""
Derive a child key with the specified index using public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes or IPoint, bytes]: Public key bytes or point (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
# Data for HMAC, same of CkdPriv() for public child key
data_bytes = pub_key.RawCompressed().ToBytes() + index.ToBytes()
# Get HMAC of data
il_bytes, ir_bytes = HmacSha512.QuickDigestHalves(pub_key.ChainCode().ToBytes(),
data_bytes)
il_int = BytesUtils.ToInteger(il_bytes)
# Get a new public key point: pub_key_point + G*iL
new_pub_key_point = pub_key.Point() + (pub_key.Curve().Generator() * il_int)
return new_pub_key_point, ir_bytes
class Bip32Slip10Ed25519Derivator(IBip32KeyDerivator):
"""
BIP32 SLIP-0010 ed25519 key derivator class.
It allows keys derivation for ed25519 curves in according to BIP32 SLIP-0010.
"""
@staticmethod
def IsPublicDerivationSupported() -> bool:
"""
Get if public derivation is supported.
Returns:
bool: True if supported, false otherwise.
"""
return False
@classmethod
def CkdPriv(cls,
priv_key: Bip32PrivateKey,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[bytes, bytes]:
"""
Derive a child key with the specified index using private derivation.
Args:
priv_key (Bip32PrivateKey object): Bip32PrivateKey object
pub_key (Bip32PublicKey object) : Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
if not index.IsHardened():
raise Bip32KeyError("Private child derivation with not-hardened index is not supported")
# Data for HMAC
data_bytes = (Bip32Slip10DerivatorConst.PRIV_KEY_PREFIX
+ priv_key.Raw().ToBytes()
+ index.ToBytes())
# Compute HMAC halves
return HmacSha512.QuickDigestHalves(priv_key.ChainCode().ToBytes(),
data_bytes)
@classmethod
def CkdPub(cls,
pub_key: Bip32PublicKey,
index: Bip32KeyIndex) -> Tuple[Union[bytes, IPoint], bytes]:
"""
Derive a child key with the specified index using public derivation.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
index (Bip32KeyIndex object) : Key index
Returns:
tuple[bytes or IPoint, bytes]: Public key bytes or point (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the index results in an invalid key
"""
raise Bip32KeyError("Public child derivation is not supported")
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_key_derivator.py",
"license": "MIT License",
"lines": 161,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_mst_key_generator.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP32 SLIP-0010 master key generation.
Reference: https://github.com/satoshilabs/slips/blob/master/slip-0010.md
"""
# Imports
from typing import Tuple
from ..base import IBip32MstKeyGenerator
from ...ecc import EllipticCurveGetter, EllipticCurveTypes
from ...utils.crypto import HmacSha512
class Bip32Slip10MstKeyGeneratorConst:
"""Class container for BIP32 SLIP-0010 master key generator constants."""
# Minimum length in bytes for seed
SEED_MIN_BYTE_LEN: int = 16
# HMAC keys for different curves
HMAC_KEY_ED25519_BYTES: bytes = b"ed25519 seed"
HMAC_KEY_NIST256P1_BYTES: bytes = b"Nist256p1 seed"
HMAC_KEY_SECP256K1_BYTES: bytes = b"Bitcoin seed"
class _Bip32Slip10MstKeyGenerator:
"""
BIP32 SLIP-0010 generic master key generator class.
It allows master keys generation in according to BIP32 SLIP-0010.
"""
@staticmethod
def GenerateFromSeed(seed_bytes: bytes,
hmac_key_bytes: bytes,
curve_type: EllipticCurveTypes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed and return a Bip32Base object.
Args:
seed_bytes (bytes) : Seed bytes
hmac_key_bytes (bytes) : HMAC key bytes
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
if len(seed_bytes) < Bip32Slip10MstKeyGeneratorConst.SEED_MIN_BYTE_LEN:
raise ValueError(f"Invalid seed length ({len(seed_bytes)})")
hmac_half_len = HmacSha512.DigestSize() // 2
priv_key_cls = EllipticCurveGetter.FromType(curve_type).PrivateKeyClass()
# Compute HMAC, retry if the resulting private key is not valid
hmac = b""
hmac_data = seed_bytes
success = False
while not success:
hmac = HmacSha512.QuickDigest(hmac_key_bytes, hmac_data)
# If private key is not valid, the new HMAC data is the current HMAC
success = priv_key_cls.IsValidBytes(hmac[:hmac_half_len])
if not success:
hmac_data = hmac
return hmac[:hmac_half_len], hmac[hmac_half_len:]
class Bip32Slip10Ed2519MstKeyGenerator(IBip32MstKeyGenerator):
"""
BIP32 SLIP-0010 ed25519 master key generator class.
It allows master keys generation in according to BIP32 SLIP-0010 for ed25519 curve.
"""
@classmethod
def GenerateFromSeed(cls,
seed_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed.
Args:
seed_bytes (bytes): Seed bytes
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
return _Bip32Slip10MstKeyGenerator.GenerateFromSeed(seed_bytes,
Bip32Slip10MstKeyGeneratorConst.HMAC_KEY_ED25519_BYTES,
EllipticCurveTypes.ED25519)
class Bip32Slip10Nist256p1MstKeyGenerator(IBip32MstKeyGenerator):
"""
BIP32 SLIP-0010 nist256p1 master key generator class.
It allows master keys generation in according to BIP32 SLIP-0010 for nist256p1 curve.
"""
@classmethod
def GenerateFromSeed(cls,
seed_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed.
Args:
seed_bytes (bytes): Seed bytes
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
return _Bip32Slip10MstKeyGenerator.GenerateFromSeed(seed_bytes,
Bip32Slip10MstKeyGeneratorConst.HMAC_KEY_NIST256P1_BYTES,
EllipticCurveTypes.NIST256P1)
class Bip32Slip10Secp256k1MstKeyGenerator(IBip32MstKeyGenerator):
"""
BIP32 SLIP-0010 secp256k1 master key generator class.
It allows master keys generation in according to BIP32 SLIP-0010 for secp256k1 curve.
"""
@classmethod
def GenerateFromSeed(cls,
seed_bytes: bytes) -> Tuple[bytes, bytes]:
"""
Generate a master key from the specified seed.
Args:
seed_bytes (bytes): Seed bytes
Returns:
tuple[bytes, bytes]: Private key bytes (index 0) and chain code bytes (index 1)
Raises:
Bip32KeyError: If the seed is not suitable for master key generation
ValueError: If seed length is not valid
"""
return _Bip32Slip10MstKeyGenerator.GenerateFromSeed(seed_bytes,
Bip32Slip10MstKeyGeneratorConst.HMAC_KEY_SECP256K1_BYTES,
EllipticCurveTypes.SECP256K1)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_mst_key_generator.py",
"license": "MIT License",
"lines": 134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_secp256k1.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for derivation scheme based on secp256k1 curve as defined by BIP32 SLIP-0010."""
# Imports
from typing import Type
from ..base import Bip32Base, IBip32KeyDerivator, IBip32MstKeyGenerator
from ..bip32_const import Bip32Const
from ..bip32_key_net_ver import Bip32KeyNetVersions
from .bip32_slip10_key_derivator import Bip32Slip10EcdsaDerivator
from .bip32_slip10_mst_key_generator import Bip32Slip10Secp256k1MstKeyGenerator
from ...ecc import EllipticCurveTypes
class Bip32Slip10Secp256k1(Bip32Base):
"""
BIP32 SLIP-0010 secp256k1 v.
It allows master keys generation and keys derivation using secp256k1 curve.
"""
@staticmethod
def CurveType() -> EllipticCurveTypes:
"""
Return the elliptic curve type.
Returns:
EllipticCurveTypes: Curve type
"""
return EllipticCurveTypes.SECP256K1
@staticmethod
def _DefaultKeyNetVersion() -> Bip32KeyNetVersions:
"""
Return the default key net version.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return Bip32Const.MAIN_NET_KEY_NET_VERSIONS
@staticmethod
def _KeyDerivator() -> Type[IBip32KeyDerivator]:
"""
Return the key derivator class.
Returns:
IBip32KeyDerivator class: Key derivator class
"""
return Bip32Slip10EcdsaDerivator
@staticmethod
def _MasterKeyGenerator() -> Type[IBip32MstKeyGenerator]:
"""
Return the master key generator class.
Returns:
IBip32MstKeyGenerator class: Master key generator class
"""
return Bip32Slip10Secp256k1MstKeyGenerator
# Deprecated: only for compatibility
Bip32Secp256k1 = Bip32Slip10Secp256k1
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip32/slip10/bip32_slip10_secp256k1.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip44/bip44.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for BIP44 keys derivation.
Reference: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
"""
# Imports
from typing import Union
from ..bip32 import Bip32KeyData, Bip32KeyIndex, Bip32KeyNetVersions, Bip32Const, Bip32Slip10Secp256k1
from ..bip44_base import Bip44Base, Bip44Changes, Bip44Levels
_BIP44_BTC_KEY_NET_VER_MAIN: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS
# from ..conf.bip44 import Bip44ConfGetter
# from ..conf.bip44 import BipCoinConf
from ..conf.common import BipCoins, BipCoinConf
from ..coin_conf import CoinsConf
from ..slip.slip44 import Slip44
from ..conf.common import DER_PATH_NON_HARDENED_FULL
# from bip_utils.ecc import IPrivateKey, IPublicKey
class Bip44Const:
"""Class container for BIP44 constants."""
# Specification name
SPEC_NAME: str = "BIP-0044"
# Purpose
PURPOSE: int = Bip32KeyIndex.HardenIndex(44)
class Bip44(Bip44Base):
"""
BIP44 class.
It allows master key generation and children keys derivation in according to BIP-0044.
"""
#
# Class methods for construction
#
@classmethod
def FromSeed(cls,
seed_bytes: bytes) -> Bip44Base:
"""
Create a Bip44Base object from the specified seed (e.g. BIP39 seed).
Args:
seed_bytes (bytes) : Seed bytes
coin_type (BipCoins): Coin type, shall be a Bip44Coins enum
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If coin type is not a Bip44Coins enum
ValueError: If the seed is too short
Bip32KeyError: If the seed is not suitable for master key generation
"""
# Bip44ConfGetter already checks the enum type
conf = BipCoinConf(
coin_names=CoinsConf.Cosmos.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
# addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Cosmos.ParamByKey("addr_hrp"),
},
)
return cls._FromSeed(seed_bytes,
conf)
@classmethod
def FromExtendedKey(cls,
ex_key_str: str) -> Bip44Base:
"""
Create a Bip44Base object from the specified extended key.
Args:
ex_key_str (str) : Extended key string
coin_type (BipCoins): Coin type, shall be a Bip44Coins enum
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If coin type is not a Bip44Coins enum
Bip32KeyError: If the extended key is not valid
"""
# Bip44ConfGetter already checks the enum type
return cls._FromExtendedKey(ex_key_str, Bip44ConfGetter.GetConfig(coin_type))
# @classmethod
# def FromPrivateKey(cls,
# priv_key: Union[bytes, IPrivateKey],
# coin_type: BipCoins,
# key_data: Bip32KeyData = Bip32KeyData()) -> Bip44Base:
# """
# Create a Bip44Base object from the specified private key and derivation data.
# If only the private key bytes are specified, the key will be considered a master key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# priv_key (bytes or IPrivateKey) : Private key
# coin_type (BipCoins) : Coin type, shall be a Bip44Coins enum
# key_data (Bip32KeyData object, optional): Key data (default: all zeros)
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# TypeError: If coin type is not a Bip44Coins enum
# Bip32KeyError: If the key is not valid
# """
# # Bip44ConfGetter already checks the enum type
# return cls._FromPrivateKey(priv_key,
# Bip44ConfGetter.GetConfig(coin_type),
# key_data)
# @classmethod
# def FromPublicKey(cls,
# pub_key: Union[bytes, IPublicKey],
# coin_type: BipCoins,
# key_data: Bip32KeyData = Bip32KeyData(depth=Bip44Levels.ACCOUNT)) -> Bip44Base:
# """
# Create a Bip44Base object from the specified public key and derivation data.
# If only the public key bytes are specified, the key will be considered an account key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# pub_key (bytes or IPublicKey) : Public key
# coin_type (BipCoins) : Coin type, shall be a Bip44Coins enum
# key_data (Bip32KeyData object, optional): Key data (default: all zeros with account depth)
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# TypeError: If coin type is not a Bip44Coins enum
# Bip32KeyError: If the key is not valid
# """
# # Bip44ConfGetter already checks the enum type
# return cls._FromPublicKey(pub_key,
# Bip44ConfGetter.GetConfig(coin_type),
# key_data)
#
# Overridden abstract methods
#
def Purpose(self) -> Bip44Base:
"""
Derive a child key from the purpose and return a new Bip44Base object.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
return self._PurposeGeneric(Bip44Const.PURPOSE)
def Coin(self) -> Bip44Base:
"""
Derive a child key from the coin type specified at construction and return a new Bip44Base object.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
return self._CoinGeneric()
def Account(self,
acc_idx: int) -> Bip44Base:
"""
Derive a child key from the specified account index and return a new Bip44Base object.
Args:
acc_idx (int): Account index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
return self._AccountGeneric(acc_idx)
def Change(self,
change_type: Bip44Changes) -> Bip44Base:
"""
Derive a child key from the specified change type and return a new Bip44Base object.
Args:
change_type (Bip44Changes): Change type, must a Bip44Changes enum
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If change type is not a Bip44Changes enum
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
return self._ChangeGeneric(change_type)
def AddressIndex(self,
addr_idx: int) -> Bip44Base:
"""
Derive a child key from the specified address index and return a new Bip44Base object.
Args:
addr_idx (int): Address index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
return self._AddressIndexGeneric(addr_idx)
@staticmethod
def SpecName() -> str:
"""
Get specification name.
Returns:
str: Specification name
"""
return Bip44Const.SPEC_NAME
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip44/bip44.py",
"license": "MIT License",
"lines": 213,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip44_base/bip44_base.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
"""Module with BIP44 base class."""
# Imports
from __future__ import annotations
from abc import ABC, abstractmethod
from enum import IntEnum, unique
from functools import lru_cache
from typing import Union
from ..bip32 import Bip32Base, Bip32KeyData, Bip32KeyIndex
from ..bip44_base.bip44_base_ex import Bip44DepthError
from ..bip44_base.bip44_keys import Bip44PrivateKey, Bip44PublicKey
from ..conf.common import BipCoinConf, BipCoins
from ..ecc import IPrivateKey, IPublicKey
@unique
class Bip44Changes(IntEnum):
"""Enumerative for BIP44 changes."""
CHAIN_EXT = 0
CHAIN_INT = 1
@unique
class Bip44Levels(IntEnum):
"""Enumerative for BIP44 levels."""
MASTER = 0
PURPOSE = 1
COIN = 2
ACCOUNT = 3
CHANGE = 4
ADDRESS_INDEX = 5
class Bip44Base(ABC):
"""
BIP44 base class.
It allows coin, account, chain and address keys generation in according to BIP44 or its extensions.
The class is meant to be derived by classes implementing BIP44 or its extensions.
"""
m_bip32_obj: Bip32Base
m_coin_conf: BipCoinConf
#
# Class methods for construction
#
@classmethod
def _FromSeed(cls,
seed_bytes: bytes,
coin_conf: BipCoinConf) -> Bip44Base:
"""
Create a Bip44Base object from the specified seed (e.g. BIP39 seed).
Args:
seed_bytes (bytes) : Seed bytes
coin_conf (BipCoinConf): BipCoinConf object
Returns:
Bip44Base object: Bip44Base object
Raises:
ValueError: If the seed is too short
Bip32KeyError: If the seed is not suitable for master key generation
"""
bip32_cls = coin_conf.Bip32Class()
return cls(bip32_cls.FromSeed(seed_bytes,
coin_conf.KeyNetVersions()),
coin_conf)
@classmethod
def _FromExtendedKey(cls,
ex_key_str: str,
coin_conf: BipCoinConf) -> Bip44Base:
"""
Create a Bip44Base object from the specified extended key.
Args:
ex_key_str (str) : Extended key string
coin_conf (BipCoinConf): BipCoinConf object
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip32KeyError: If the extended key is not valid
"""
bip32_cls = coin_conf.Bip32Class()
return cls(bip32_cls.FromExtendedKey(ex_key_str, coin_conf.KeyNetVersions()),
coin_conf)
# @classmethod
# def _FromPrivateKey(cls,
# priv_key: Union[bytes, IPrivateKey],
# coin_conf: BipCoinConf,
# key_data: Bip32KeyData) -> Bip44Base:
# """
# Create a Bip44Base object from the specified private key and derivation data.
# If only the private key bytes are specified, the key will be considered a master key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# priv_key (bytes or IPrivateKey): Private key
# coin_conf (BipCoinConf) : BipCoinConf object
# key_data (Bip32KeyData object) : Key data
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# Bip32KeyError: If the key is not valid
# """
# bip32_cls = coin_conf.Bip32Class()
# return cls(bip32_cls.FromPrivateKey(priv_key,
# key_data,
# coin_conf.KeyNetVersions()),
# coin_conf)
# @classmethod
# def _FromPublicKey(cls,
# pub_key: Union[bytes, IPublicKey],
# coin_conf: BipCoinConf,
# key_data: Bip32KeyData) -> Bip44Base:
# """
# Create a Bip44Base object from the specified public key and derivation data.
# If only the public key bytes are specified, the key will be considered an account key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# pub_key (bytes or IPublicKey) : Public key
# coin_conf (BipCoinConf) : BipCoinConf object
# key_data (Bip32KeyData object) : Key data
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# Bip32KeyError: If the key is not valid
# """
# bip32_cls = coin_conf.Bip32Class()
# return cls(bip32_cls.FromPublicKey(pub_key,
# key_data,
# coin_conf.KeyNetVersions()),
# coin_conf)
#
# Public methods
#
def __init__(self,
bip32_obj: Bip32Base,
coin_conf: BipCoinConf) -> None:
"""
Construct class.
Args:
bip32_obj (Bip32Base object): Bip32Base object
coin_conf (BipCoinConf) : BipCoinConf object
Returns:
Bip44DepthError: If the Bip32 object depth is not valid
"""
depth = bip32_obj.Depth()
# If the Bip32 is public-only, the depth shall start from the account level because hardened derivation is
# used below it, which is not possible with public keys
if bip32_obj.IsPublicOnly():
if depth < Bip44Levels.ACCOUNT or depth > Bip44Levels.ADDRESS_INDEX:
raise Bip44DepthError(
f"Depth of the public-only Bip object ({depth}) is below account level or "
f"beyond address index level"
)
# If the Bip32 object is not public-only, any depth is fine as long as it is not greater
# than address index level
else:
if depth < 0 or depth > Bip44Levels.ADDRESS_INDEX:
raise Bip44DepthError(
f"Depth of the Bip object ({depth}) is invalid or beyond address index level"
)
# Finally, initialize class
self.m_bip32_obj = bip32_obj
self.m_coin_conf = coin_conf
@lru_cache()
def PublicKey(self) -> Bip44PublicKey:
"""
Return the public key.
Returns:
Bip44PublicKey object: Bip44PublicKey object
"""
return Bip44PublicKey(self.m_bip32_obj.PublicKey(),
self.m_coin_conf)
@lru_cache()
def PrivateKey(self) -> Bip44PrivateKey:
"""
Return the private key.
Returns:
Bip44PrivateKey object: Bip44PrivateKey object
Raises:
Bip32KeyError: If the Bip32 object is public-only
"""
return Bip44PrivateKey(self.m_bip32_obj.PrivateKey(),
self.m_coin_conf)
def Bip32Object(self) -> Bip32Base:
"""
Return the BIP32 object.
Returns:
Bip32Base object: Bip32Base object
"""
return self.m_bip32_obj
def CoinConf(self) -> BipCoinConf:
"""
Get coin configuration.
Returns:
BipCoinConf object: BipCoinConf object
"""
return self.m_coin_conf
def IsPublicOnly(self) -> bool:
"""
Get if it's public-only.
Returns:
bool: True if public-only, false otherwise
"""
return self.m_bip32_obj.IsPublicOnly()
def Level(self) -> Bip44Levels:
"""
Return the current level.
Returns:
Bip44Levels: Current level
"""
return Bip44Levels(self.m_bip32_obj.Depth().ToInt())
def IsLevel(self,
level: Bip44Levels) -> bool:
"""
Return if the current level is the specified one.
Args:
level (Bip44Levels): Level to be checked
Returns:
bool: True if it's the specified level, false otherwise
Raises:
TypeError: If the level index is not a Bip44Levels enum
"""
if not isinstance(level, Bip44Levels):
raise TypeError("Level is not an enumerative of Bip44Levels")
return self.m_bip32_obj.Depth() == level
def DeriveDefaultPath(self) -> Bip44Base:
"""
Derive the default coin path and return a new Bip44Base object.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
# Derive purpose and coin by default
bip_obj = self.Purpose().Coin()
# Derive the remaining path
return self.__class__(bip_obj.m_bip32_obj.DerivePath(bip_obj.m_coin_conf.DefaultPath()),
bip_obj.m_coin_conf)
#
# Protected class methods
#
def _PurposeGeneric(self,
purpose: int) -> Bip44Base:
"""
Derive a child key from the purpose and return a new Bip44Base object.
It shall be called from a child class.
Args:
purpose (int): Purpose
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
if not self.IsLevel(Bip44Levels.MASTER):
raise Bip44DepthError(
f"Current depth ({self.m_bip32_obj.Depth().ToInt()}) is not suitable for deriving purpose"
)
return self.__class__(self.m_bip32_obj.ChildKey(purpose),
self.m_coin_conf)
def _CoinGeneric(self) -> Bip44Base:
"""
Derive a child key from the coin type specified at construction and return a new Bip44Base object.
It shall be called from a child class.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
if not self.IsLevel(Bip44Levels.PURPOSE):
raise Bip44DepthError(
f"Current depth ({self.m_bip32_obj.Depth().ToInt()}) is not suitable for deriving coin"
)
coin_idx = self.m_coin_conf.CoinIndex()
return self.__class__(self.m_bip32_obj.ChildKey(Bip32KeyIndex.HardenIndex(coin_idx)),
self.m_coin_conf)
def _AccountGeneric(self,
acc_idx: int) -> Bip44Base:
"""
Derive a child key from the specified account index and return a new Bip44Base object.
It shall be called from a child class.
Args:
acc_idx (int): Account index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
if not self.IsLevel(Bip44Levels.COIN):
raise Bip44DepthError(
f"Current depth ({self.m_bip32_obj.Depth().ToInt()}) is not suitable for deriving account"
)
return self.__class__(self.m_bip32_obj.ChildKey(Bip32KeyIndex.HardenIndex(acc_idx)),
self.m_coin_conf)
def _ChangeGeneric(self,
change_type: Bip44Changes) -> Bip44Base:
"""
Derive a child key from the specified change type and return a new Bip44Base object.
It shall be called from a child class.
Args:
change_type (Bip44Changes): Change type, must a Bip44Changes enum
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If change type is not a Bip44Changes enum
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
if not isinstance(change_type, Bip44Changes):
raise TypeError("Change index is not an enumerative of Bip44Changes")
if not self.IsLevel(Bip44Levels.ACCOUNT):
raise Bip44DepthError(
f"Current depth ({self.m_bip32_obj.Depth().ToInt()}) is not suitable for deriving change"
)
# Use hardened derivation if not-hardended is not supported
if not self.m_bip32_obj.IsPublicDerivationSupported():
change_idx = Bip32KeyIndex.HardenIndex(int(change_type))
else:
change_idx = int(change_type)
return self.__class__(self.m_bip32_obj.ChildKey(change_idx),
self.m_coin_conf)
def _AddressIndexGeneric(self,
addr_idx: int) -> Bip44Base:
"""
Derive a child key from the specified address index and return a new Bip44Base object.
It shall be called from a child class.
Args:
addr_idx (int): Address index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If the current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
if not self.IsLevel(Bip44Levels.CHANGE):
raise Bip44DepthError(
f"Current depth ({self.m_bip32_obj.Depth().ToInt()}) is not suitable for deriving address"
)
# Use hardened derivation if not-hardended is not supported
if not self.m_bip32_obj.IsPublicDerivationSupported():
addr_idx = Bip32KeyIndex.HardenIndex(addr_idx)
return self.__class__(self.m_bip32_obj.ChildKey(addr_idx),
self.m_coin_conf)
#
# Abstract methods
#
@classmethod
@abstractmethod
def FromSeed(cls,
seed_bytes: bytes,
coin_type: BipCoins) -> Bip44Base:
"""
Create a Bip44Base object from the specified seed (e.g. BIP39 seed).
The test net flag is automatically set when the coin is derived. However, if you want to get the correct master
or purpose keys, you have to specify here if it's a test net.
Args:
seed_bytes (bytes) : Seed bytes
coin_type (BipCoins): Coin type (the type depends on the specific child class)
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If coin type is not of the correct type
ValueError: If the seed is too short
Bip32KeyError: If the seed is not suitable for master key generation
"""
@classmethod
@abstractmethod
def FromExtendedKey(cls,
ex_key_str: str,
coin_type: BipCoins) -> Bip44Base:
"""
Create a Bip44Base object from the specified extended key.
Args:
ex_key_str (str) : Extended key string
coin_type (BipCoins): Coin type (the type depends on the specific child class)
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If coin type is not of the correct type
Bip32KeyError: If the extended key is not valid
"""
# @classmethod
# @abstractmethod
# def FromPrivateKey(cls,
# priv_key: Union[bytes, IPrivateKey],
# coin_type: BipCoins,
# key_data: Bip32KeyData) -> Bip44Base:
# """
# Create a Bip44Base object from the specified private key and derivation data.
# If only the private key bytes are specified, the key will be considered a master key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# priv_key (bytes or IPrivateKey): Private key
# coin_type (BipCoins) : Coin type, shall be a Bip44Coins enum
# key_data (Bip32KeyData object) : Key data
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# TypeError: If coin type is not a Bip44Coins enum
# Bip32KeyError: If the key is not valid
# """
# @classmethod
# @abstractmethod
# def FromPublicKey(cls,
# pub_key: Union[bytes, IPublicKey],
# coin_type: BipCoins,
# key_data: Bip32KeyData) -> Bip44Base:
# """
# Create a Bip44Base object from the specified public key and derivation data.
# If only the public key bytes are specified, the key will be considered an account key with
# the chain code set to zero, since there is no way to recover the key derivation data.
# Args:
# pub_key (bytes or IPublicKey) : Public key
# coin_type (BipCoins) : Coin type, shall be a Bip44Coins enum
# key_data (Bip32KeyData object): Key data
# Returns:
# Bip44Base object: Bip44Base object
# Raises:
# TypeError: If coin type is not a Bip44Coins enum
# Bip32KeyError: If the key is not valid
# """
@abstractmethod
def Purpose(self) -> Bip44Base:
"""
Derive a child key from the purpose and return a new Bip44Base object.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
@abstractmethod
def Coin(self) -> Bip44Base:
"""
Derive a child key from the coin type specified at construction and return a new Bip44Base object.
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
@abstractmethod
def Account(self,
acc_idx: int) -> Bip44Base:
"""
Derive a child key from the specified account index and return a new Bip44Base object.
Args:
acc_idx (int): Account index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
@abstractmethod
def Change(self,
change_type: Bip44Changes) -> Bip44Base:
"""
Derive a child key from the specified change type and return a new Bip44Base object.
Args:
change_type (Bip44Changes): Change type, must a Bip44Changes enum
Returns:
Bip44Base object: Bip44Base object
Raises:
TypeError: If change type is not a Bip44Changes enum
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
@abstractmethod
def AddressIndex(self,
addr_idx: int) -> Bip44Base:
"""
Derive a child key from the specified address index and return a new Bip44Base object.
Args:
addr_idx (int): Address index
Returns:
Bip44Base object: Bip44Base object
Raises:
Bip44DepthError: If current depth is not suitable for deriving keys
Bip32KeyError: If the derivation results in an invalid key
"""
@staticmethod
@abstractmethod
def SpecName() -> str:
"""
Get specification name.
Returns:
str: Specification name
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip44_base/bip44_base.py",
"license": "MIT License",
"lines": 501,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip44_base/bip44_base_ex.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP44 exceptions."""
class Bip44DepthError(Exception):
"""Exception in case of derivation from wrong depth."""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip44_base/bip44_base_ex.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip44_base/bip44_keys.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP44 keys handling."""
# Imports
from functools import lru_cache
# from ..addr import AdaShelleyAddrEncoder, XmrAddrEncoder
from ..bip32 import Bip32ChainCode, Bip32PrivateKey, Bip32PublicKey
from ..conf.common import BipCoinConf
from ..utils.misc import DataBytes
from ..wif import WifEncoder, WifPubKeyModes
class Bip44PublicKey:
"""
BIP44 public key class.
It contains Bip32PublicKey and add the possibility to compute the address from the coin type.
"""
m_pub_key: Bip32PublicKey
m_coin_conf: BipCoinConf
def __init__(self,
pub_key: Bip32PublicKey,
coin_conf: BipCoinConf) -> None:
"""
Construct class.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
coin_conf (BipCoinConf object) : BipCoinConf object
Raises:
ValueError: If the key elliptic curve is different from the coin configuration one
"""
if pub_key.CurveType() != coin_conf.Bip32Class().CurveType():
raise ValueError(
f"The public key elliptic curve ({pub_key.CurveType()}) shall match "
f"the coin configuration one ({coin_conf.Bip32Class().CurveType()})"
)
self.m_pub_key = pub_key
self.m_coin_conf = coin_conf
def Bip32Key(self) -> Bip32PublicKey:
"""
Return the BIP32 key object.
Returns:
Bip32PublicKey object: BIP32 key object
"""
return self.m_pub_key
def ToExtended(self) -> str:
"""
Return key in serialized extended format.
Returns:
str: Key in serialized extended format
"""
return self.m_pub_key.ToExtended()
def ChainCode(self) -> Bip32ChainCode:
"""
Return the chain code.
Returns:
Bip32ChainCode object: Bip32ChainCode object
"""
return self.m_pub_key.ChainCode()
def RawCompressed(self) -> DataBytes:
"""
Return raw compressed public key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_pub_key.RawCompressed()
def RawUncompressed(self) -> DataBytes:
"""
Return raw uncompressed public key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_pub_key.RawUncompressed()
@lru_cache()
def ToAddress(self) -> str:
"""
Return the address correspondent to the public key.
Returns:
str: Address string
"""
addr_cls = self.m_coin_conf.AddrClass()
pub_key_obj = self.m_pub_key.KeyObject()
# # Exception for Cardano
# if addr_cls is AdaShelleyAddrEncoder:
# raise ValueError("Use the CardanoShelley class to get Cardano Shelley addresses")
# # Exception for Monero
# if addr_cls is XmrAddrEncoder:
# raise ValueError("Use the Monero class to get Monero addresses")
return addr_cls.EncodeKey(pub_key_obj,
**self.m_coin_conf.AddrParamsWithResolvedCalls(self.m_pub_key))
class Bip44PrivateKey:
"""
BIP44 private key class.
It contains Bip32PrivateKey and add the possibility to compute the WIF from the coin type.
"""
m_priv_key: Bip32PrivateKey
m_coin_conf: BipCoinConf
def __init__(self,
priv_key: Bip32PrivateKey,
coin_conf: BipCoinConf) -> None:
"""
Construct class.
Args:
priv_key (Bip32PrivateKey object): Bip32PrivateKey object
coin_conf (BipCoinConf object) : BipCoinConf object
Raises:
ValueError: If the key elliptic curve is different from the coin configuration one
"""
if priv_key.CurveType() != coin_conf.Bip32Class().CurveType():
raise ValueError(
f"The private key elliptic curve ({priv_key.CurveType()}) shall match "
f"the coin configuration one ({coin_conf.Bip32Class().CurveType()})"
)
self.m_priv_key = priv_key
self.m_coin_conf = coin_conf
def Bip32Key(self) -> Bip32PrivateKey:
"""
Return the BIP32 key object.
Returns:
Bip32PublicKey object: BIP32 key object
"""
return self.m_priv_key
def ToExtended(self) -> str:
"""
Return key in serialized extended format.
Returns:
str: Key in serialized extended format
"""
return self.m_priv_key.ToExtended()
def ChainCode(self) -> Bip32ChainCode:
"""
Return the chain code.
Returns:
Bip32ChainCode object: Bip32ChainCode object
"""
return self.m_priv_key.ChainCode()
def Raw(self) -> DataBytes:
"""
Return raw compressed public key.
Returns:
DataBytes object: DataBytes object
"""
return self.m_priv_key.Raw()
@lru_cache()
def PublicKey(self) -> Bip44PublicKey:
"""
Get the public key correspondent to the private one.
Returns:
Bip44PublicKey object: Bip44PublicKey object
"""
return Bip44PublicKey(self.m_priv_key.PublicKey(),
self.m_coin_conf)
@lru_cache()
def ToWif(self,
pub_key_mode: WifPubKeyModes = WifPubKeyModes.COMPRESSED) -> str:
"""
Return key in WIF format.
Args:
pub_key_mode (WifPubKeyModes): Specify if the private key corresponds to a compressed public key
Returns:
str: Key in WIF format
"""
wif_net_ver = self.m_coin_conf.WifNetVersion()
return (WifEncoder.Encode(self.m_priv_key.Raw().ToBytes(), wif_net_ver, pub_key_mode)
if wif_net_ver is not None
else "")
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/bip44_base/bip44_keys.py",
"license": "MIT License",
"lines": 180,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/coin_conf/coin_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for generic coins configuration handling."""
# Imports
from typing import Any, Dict
from ..utils.conf import CoinNames as ConfCoinNames
class CoinConf:
"""Coin configuration class."""
m_coin_name: ConfCoinNames
m_params: Dict[str, Any]
def __init__(self,
coin_name: ConfCoinNames,
params: Dict[str, Any]) -> None:
"""
Construct class.
Args:
coin_name (CoinNames object): Coin names
params (dict) : SS58 format
"""
self.m_coin_name = coin_name
self.m_params = params
def CoinNames(self) -> ConfCoinNames:
"""
Get coin names.
Returns:
CoinNames object: CoinNames object
"""
return self.m_coin_name
def ParamByKey(self,
key: str) -> Any:
"""
Get the parameter by key.
Args:
key (str): Parameter key
Returns:
Any: Parameter value
"""
return self.m_params[key]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/coin_conf/coin_conf.py",
"license": "MIT License",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/coin_conf/coins_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with generic coins configuration for all other modules."""
# Imports
from .coin_conf import CoinConf
from ..slip.slip173 import Slip173
from ..utils.conf import CoinNames
# Bitcoin constants used by different coins
# Main net
_BTC_P2PKH_NET_VER_MN: bytes = b"\x00"
_BTC_P2SH_NET_VER_MN: bytes = b"\x05"
_BTC_P2WPKH_HRP_MN: str = Slip173.BITCOIN_MAINNET
_BTC_P2WPKH_WIT_VER_MN: int = 0
_BTC_P2TR_HRP_MN: str = Slip173.BITCOIN_MAINNET
_BTC_P2TR_WIT_VER_MN: int = 1
_BTC_WIF_NET_VER_MN: bytes = b"\x80"
# Test net
_BTC_P2PKH_NET_VER_TN: bytes = b"\x6f"
_BTC_P2SH_NET_VER_TN: bytes = b"\xc4"
_BTC_P2WPKH_HRP_TN: str = Slip173.BITCOIN_TESTNET
_BTC_P2WPKH_WIT_VER_TN: int = 0
_BTC_P2TR_HRP_TN: str = Slip173.BITCOIN_TESTNET
_BTC_P2TR_WIT_VER_TN: int = 1
_BTC_WIF_NET_VER_TN: bytes = b"\xef"
# Regtest
_BTC_P2PKH_NET_VER_RT: bytes = _BTC_P2PKH_NET_VER_TN
_BTC_P2SH_NET_VER_RT: bytes = _BTC_P2SH_NET_VER_TN
_BTC_P2WPKH_HRP_RT: str = Slip173.BITCOIN_REGTEST
_BTC_P2WPKH_WIT_VER_RT: int = _BTC_P2TR_WIT_VER_TN
_BTC_P2TR_HRP_RT: str = Slip173.BITCOIN_REGTEST
_BTC_P2TR_WIT_VER_RT: int = _BTC_P2TR_WIT_VER_TN
_BTC_WIF_NET_VER_RT: bytes = _BTC_WIF_NET_VER_TN
class CoinsConf:
"""Class container for coins configuration."""
# # Configuration for Acala
# Acala: CoinConf = CoinConf(
# coin_name=CoinNames("Acala", "ACA"),
# params={
# "addr_ss58_format": 10,
# },
# )
# # Configuration for Akash Network
# AkashNetwork: CoinConf = CoinConf(
# coin_name=CoinNames("Akash Network", "AKT"),
# params={
# "addr_hrp": Slip173.AKASH_NETWORK,
# },
# )
# # Configuration for Algorand
# Algorand: CoinConf = CoinConf(
# coin_name=CoinNames("Algorand", "ALGO"),
# params={},
# )
# # Configuration for Aptos
# Aptos: CoinConf = CoinConf(
# coin_name=CoinNames("Aptos", "APTOS"),
# params={
# "addr_prefix": "0x",
# },
# )
# # Configuration for Arbitrum
# Arbitrum: CoinConf = CoinConf(
# coin_name=CoinNames("Arbitrum", "ARB"),
# params={},
# )
# # Configuration for Avax C-Chain
# AvaxCChain: CoinConf = CoinConf(
# coin_name=CoinNames("Avax C-Chain", "AVAX"),
# params={},
# )
# # Configuration for Avax P-Chain
# AvaxPChain: CoinConf = CoinConf(
# coin_name=CoinNames("Avax P-Chain", "AVAX"),
# params={
# "addr_hrp": "avax",
# "addr_prefix": "P-",
# },
# )
# # Configuration for Avax X-Chain
# AvaxXChain: CoinConf = CoinConf(
# coin_name=CoinNames("Avax X-Chain", "AVAX"),
# params={
# "addr_hrp": "avax",
# "addr_prefix": "X-",
# },
# )
# # Configuration for Axelar
# Axelar: CoinConf = CoinConf(
# coin_name=CoinNames("Axelar", "AXL"),
# params={
# "addr_hrp": Slip173.AXELAR,
# },
# )
# # Configuration for Band Protocol
# BandProtocol: CoinConf = CoinConf(
# coin_name=CoinNames("Band Protocol", "BAND"),
# params={
# "addr_hrp": Slip173.BAND_PROTOCOL,
# },
# )
# # Configuration for Bifrost
# Bifrost: CoinConf = CoinConf(
# coin_name=CoinNames("Bifrost", "BNC"),
# params={
# "addr_ss58_format": 6,
# },
# )
# # Configuration for Binance Chain
# BinanceChain: CoinConf = CoinConf(
# coin_name=CoinNames("Binance Chain", "BNB"),
# params={
# "addr_hrp": Slip173.BINANCE_CHAIN,
# },
# )
# # Configuration for Binance Smart Chain
# BinanceSmartChain: CoinConf = CoinConf(
# coin_name=CoinNames("Binance Smart Chain", "BNB"),
# params={},
# )
# Configuration for Bitcoin main net
BitcoinMainNet: CoinConf = CoinConf(
coin_name=CoinNames("Bitcoin", "BTC"),
params={
"p2pkh_net_ver": _BTC_P2PKH_NET_VER_MN,
"p2sh_net_ver": _BTC_P2SH_NET_VER_MN,
"p2wpkh_hrp": _BTC_P2WPKH_HRP_MN,
"p2wpkh_wit_ver": _BTC_P2WPKH_WIT_VER_MN,
"p2tr_hrp": _BTC_P2TR_HRP_MN,
"p2tr_wit_ver": _BTC_P2TR_WIT_VER_MN,
"wif_net_ver": _BTC_WIF_NET_VER_MN,
},
)
# # Configuration for Bitcoin test net
# BitcoinTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin TestNet", "BTC"),
# params={
# "p2pkh_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_net_ver": _BTC_P2SH_NET_VER_TN,
# "p2wpkh_hrp": _BTC_P2WPKH_HRP_TN,
# "p2wpkh_wit_ver": _BTC_P2WPKH_WIT_VER_TN,
# "p2tr_hrp": _BTC_P2TR_HRP_TN,
# "p2tr_wit_ver": _BTC_P2TR_WIT_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Bitcoin regtest
# BitcoinRegTest: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin RegTest", "BTC"),
# params={
# "p2pkh_net_ver": _BTC_P2PKH_NET_VER_RT,
# "p2sh_net_ver": _BTC_P2SH_NET_VER_RT,
# "p2wpkh_hrp": _BTC_P2WPKH_HRP_RT,
# "p2wpkh_wit_ver": _BTC_P2WPKH_WIT_VER_RT,
# "p2tr_hrp": _BTC_P2TR_HRP_RT,
# "p2tr_wit_ver": _BTC_P2TR_WIT_VER_RT,
# "wif_net_ver": _BTC_WIF_NET_VER_RT,
# },
# )
# # Configuration for Bitcoin Cash main net
# BitcoinCashMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin Cash", "BCH"),
# params={
# "p2pkh_std_hrp": "bitcoincash",
# "p2pkh_std_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2sh_std_hrp": "bitcoincash",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_MN,
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Bitcoin Cash test net
# BitcoinCashTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin Cash TestNet", "BCH"),
# params={
# "p2pkh_std_hrp": "bchtest",
# "p2pkh_std_net_ver": b"\x00",
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_std_hrp": "bchtest",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Bitcoin Cash Simple Ledger Protocol main net
# BitcoinCashSlpMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin Cash SLP", "SLP"),
# params={
# "p2pkh_std_hrp": "simpleledger",
# "p2pkh_std_net_ver": b"\x00",
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2sh_std_hrp": "simpleledger",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_MN,
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Bitcoin Cash Simple Ledger Protocol test net
# BitcoinCashSlpTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Bitcoin Cash SLP TestNet", "SLP"),
# params={
# "p2pkh_std_hrp": "slptest",
# "p2pkh_std_net_ver": b"\x00",
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_std_hrp": "slptest",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Bitcoin SV main net
# BitcoinSvMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("BitcoinSV", "BSV"),
# params={
# "p2pkh_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2sh_net_ver": _BTC_P2SH_NET_VER_MN,
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Bitcoin SV test net
# BitcoinSvTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("BitcoinSV TestNet", "BSV"),
# params={
# "p2pkh_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_net_ver": _BTC_P2SH_NET_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Cardano main net
# CardanoMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Cardano", "ADA"),
# params={
# "addr_hrp": "addr",
# "staking_addr_hrp": "stake",
# },
# )
# # Configuration for Cardano test
# CardanoTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Cardano TestNet", "ADA"),
# params={
# "addr_hrp": "addr_test",
# "staking_addr_hrp": "stake_test",
# },
# )
# # Configuration for Celestia
# Celestia: CoinConf = CoinConf(
# coin_name=CoinNames("Celestia", "TIA"),
# params={
# "addr_hrp": Slip173.CELESTIA,
# },
# )
# # Configuration for Celo
# Celo: CoinConf = CoinConf(
# coin_name=CoinNames("Celo", "CELO"),
# params={},
# )
# # Configuration for Certik
# Certik: CoinConf = CoinConf(
# coin_name=CoinNames("Certik", "CTK"),
# params={
# "addr_hrp": Slip173.CERTIK,
# },
# )
# # Configuration for ChainX
# ChainX: CoinConf = CoinConf(
# coin_name=CoinNames("ChainX", "PCX"),
# params={
# "addr_ss58_format": 44,
# },
# )
# # Configuration for Chihuahua
# Chihuahua: CoinConf = CoinConf(
# coin_name=CoinNames("Chihuahua", "HUAHUA"),
# params={
# "addr_hrp": Slip173.CHIHUAHUA,
# },
# )
# Configuration for Cosmos
Cosmos: CoinConf = CoinConf(
coin_name=CoinNames("Cosmos", "ATOM"),
params={
"addr_hrp": Slip173.COSMOS,
},
)
# # Configuration for Dash main net
# DashMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Dash", "DASH"),
# params={
# "p2pkh_net_ver": b"\x4c",
# "p2sh_net_ver": b"\x10",
# "wif_net_ver": b"\xcc",
# },
# )
# # Configuration for Dash test net
# DashTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Dash TestNet", "DASH"),
# params={
# "p2pkh_net_ver": b"\x8c",
# "p2sh_net_ver": b"\x13",
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Dogecoin main net
# DogecoinMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Dogecoin", "DOGE"),
# params={
# "p2pkh_net_ver": b"\x1e",
# "p2sh_net_ver": b"\x16",
# "wif_net_ver": b"\x9e",
# },
# )
# # Configuration for Dogecoin test net
# DogecoinTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Dogecoin TestNet", "DOGE"),
# params={
# "p2pkh_net_ver": b"\x71",
# "p2sh_net_ver": _BTC_P2SH_NET_VER_TN,
# "wif_net_ver": b"\xf1",
# },
# )
# # Configuration for dYdX
# DYDX: CoinConf = CoinConf(
# coin_name=CoinNames("dYdX", "DYDX"),
# params={
# "addr_hrp": Slip173.DYDX,
# },
# )
# # Configuration for eCash main net
# EcashMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("eCash", "XEC"),
# params={
# "p2pkh_std_hrp": "ecash",
# "p2pkh_std_net_ver": b"\x00",
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2sh_std_hrp": "ecash",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_MN,
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for eCash test net
# EcashTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("eCash TestNet", "XEC"),
# params={
# "p2pkh_std_hrp": "ectest",
# "p2pkh_std_net_ver": b"\x00",
# "p2pkh_legacy_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_std_hrp": "ectest",
# "p2sh_std_net_ver": b"\x08",
# "p2sh_legacy_net_ver": _BTC_P2SH_NET_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Edgeware
# Edgeware: CoinConf = CoinConf(
# coin_name=CoinNames("Edgeware", "EDG"),
# params={
# "addr_ss58_format": 7,
# },
# )
# # Configuration for Elrond
# Elrond: CoinConf = CoinConf(
# coin_name=CoinNames("MultiversX", "EGLD"),
# params={
# "addr_hrp": Slip173.ELROND,
# },
# )
# # Configuration for Eos
# Eos: CoinConf = CoinConf(
# coin_name=CoinNames("EOS", "EOS"),
# params={
# "addr_prefix": "EOS",
# },
# )
# # Configuration for Ergo main net
# ErgoMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Ergo", "ERGO"),
# params={},
# )
# # Configuration for Ergo test net
# ErgoTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Ergo TestNet", "ERGO"),
# params={},
# )
# # Configuration for Ethereum
# Ethereum: CoinConf = CoinConf(
# coin_name=CoinNames("Ethereum", "ETH"),
# params={
# "addr_prefix": "0x",
# },
# )
# # Configuration for Ethereum Classic
# EthereumClassic: CoinConf = CoinConf(
# coin_name=CoinNames("Ethereum Classic", "ETC"),
# params={},
# )
# # Configuration for Fantom Opera
# FantomOpera: CoinConf = CoinConf(
# coin_name=CoinNames("Fantom Opera", "FTM"),
# params={},
# )
# # Configuration for Fetch.ai
# FetchAi: CoinConf = CoinConf(
# coin_name=CoinNames("Fetch.ai", "FET"),
# params={
# "addr_hrp": Slip173.FETCH_AI,
# },
# )
# # Configuration for Filecoin
# Filecoin: CoinConf = CoinConf(
# coin_name=CoinNames("Filecoin", "FIL"),
# params={
# "addr_prefix": "f",
# },
# )
# # Configuration for generic Substrate coin
# GenericSubstrate: CoinConf = CoinConf(
# coin_name=CoinNames("Generic Substrate", ""),
# params={
# "addr_ss58_format": 42,
# },
# )
# # Configuration for Harmony One
# HarmonyOne: CoinConf = CoinConf(
# coin_name=CoinNames("Harmony One", "ONE"),
# params={
# "addr_hrp": Slip173.HARMONY_ONE,
# },
# )
# # Configuration for Huobi Chain
# HuobiChain: CoinConf = CoinConf(
# coin_name=CoinNames("Huobi Token", "HT"),
# params={},
# )
# # Configuration for Icon
# Icon: CoinConf = CoinConf(
# coin_name=CoinNames("Icon", "ICX"),
# params={
# "addr_prefix": "hx",
# },
# )
# # Configuration for Injective
# Injective: CoinConf = CoinConf(
# coin_name=CoinNames("Injective", "INJ"),
# params={
# "addr_hrp": Slip173.INJECTIVE,
# },
# )
# # Configuration for IRISnet
# IrisNet: CoinConf = CoinConf(
# coin_name=CoinNames("IRIS Network", "IRIS"),
# params={
# "addr_hrp": Slip173.IRIS_NETWORK,
# },
# )
# # Configuration for Karura
# Karura: CoinConf = CoinConf(
# coin_name=CoinNames("Karura", "KAR"),
# params={
# "addr_ss58_format": 8,
# },
# )
# # Configuration for Kava
# Kava: CoinConf = CoinConf(
# coin_name=CoinNames("Kava", "KAVA"),
# params={
# "addr_hrp": Slip173.KAVA,
# },
# )
# # Configuration for Kusama
# Kusama: CoinConf = CoinConf(
# coin_name=CoinNames("Kusama", "KSM"),
# params={
# "addr_ss58_format": 2,
# },
# )
# # Configuration for Litecoin main net
# LitecoinMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Litecoin", "LTC"),
# params={
# "p2pkh_std_net_ver": b"\x30",
# "p2pkh_depr_net_ver": _BTC_P2PKH_NET_VER_MN,
# "p2sh_std_net_ver": b"\x32",
# "p2sh_depr_net_ver": _BTC_P2SH_NET_VER_MN,
# "p2wpkh_hrp": Slip173.LITECOIN_MAINNET,
# "p2wpkh_wit_ver": _BTC_P2WPKH_WIT_VER_MN,
# "wif_net_ver": b"\xb0",
# },
# )
# # Configuration for Litecoin test net
# LitecoinTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Litecoin TestNet", "LTC"),
# params={
# "p2pkh_std_net_ver": b"\x6f",
# "p2pkh_depr_net_ver": _BTC_P2PKH_NET_VER_TN,
# "p2sh_std_net_ver": b"\x3a",
# "p2sh_depr_net_ver": _BTC_P2SH_NET_VER_TN,
# "p2wpkh_hrp": Slip173.LITECOIN_TESTNET,
# "p2wpkh_wit_ver": _BTC_P2WPKH_WIT_VER_TN,
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Metis
# Metis: CoinConf = CoinConf(
# coin_name=CoinNames("Metis", "METIS"),
# params={},
# )
# # Configuration for Monero main net
# MoneroMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Monero", "XMR"),
# params={
# "addr_net_ver": b"\x12",
# "addr_int_net_ver": b"\x13",
# "subaddr_net_ver": b"\x2a",
# },
# )
# # Configuration for Monero stage net
# MoneroStageNet: CoinConf = CoinConf(
# coin_name=CoinNames("Monero StageNet", "XMR"),
# params={
# "addr_net_ver": b"\x18",
# "addr_int_net_ver": b"\x19",
# "subaddr_net_ver": b"\x24",
# },
# )
# # Configuration for Monero test net
# MoneroTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Monero TestNet", "XMR"),
# params={
# "addr_net_ver": b"\x35",
# "addr_int_net_ver": b"\x36",
# "subaddr_net_ver": b"\x3f",
# },
# )
# # Configuration for Moonbeam
# Moonbeam: CoinConf = CoinConf(
# coin_name=CoinNames("Moonbeam", "GLMR"),
# params={
# "addr_ss58_format": 1284,
# },
# )
# # Configuration for Moonriver
# Moonriver: CoinConf = CoinConf(
# coin_name=CoinNames("Moonriver", "MOVR"),
# params={
# "addr_ss58_format": 1285,
# },
# )
# # Configuration for Nano
# Nano: CoinConf = CoinConf(
# coin_name=CoinNames("Nano", "NANO"),
# params={
# "addr_prefix": "nano_",
# },
# )
# # Configuration for Near Protocol
# NearProtocol: CoinConf = CoinConf(
# coin_name=CoinNames("Near Protocol", "NEAR"),
# params={},
# )
# # For compatibility, later assigned to NeoLegacy
# Neo: CoinConf
# # Configuration for Neo legacy
# NeoLegacy: CoinConf = CoinConf(
# coin_name=CoinNames("NEO", "NEO"),
# params={
# "addr_ver": b"\x17",
# "addr_prefix": b"\x21",
# "addr_suffix": b"\xac",
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Neo N3
# NeoN3: CoinConf = CoinConf(
# coin_name=CoinNames("NEO", "NEO"),
# params={
# "addr_ver": b"\x35",
# "addr_prefix": b"\x0c\x21",
# "addr_suffix": b"\x41\x56\xe7\xb3\x27",
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Neutron
# Neutron: CoinConf = CoinConf(
# coin_name=CoinNames("Neutron", "NTRN"),
# params={
# "addr_hrp": Slip173.NEUTRON,
# },
# )
# # Configuration for Nimiq
# Nimiq: CoinConf = CoinConf(
# coin_name=CoinNames("Nimiq", "NIM"),
# params={
# "addr_prefix": "NQ"
# },
# )
# # Configuration for Nine Chronicles Gold
# NineChroniclesGold: CoinConf = CoinConf(
# coin_name=CoinNames("NineChroniclesGold", "NCG"),
# params={},
# )
# # Configuration for OKEx Chain
# OkexChain: CoinConf = CoinConf(
# coin_name=CoinNames("OKExChain", "OKT"),
# params={
# "addr_hrp": Slip173.OKEX_CHAIN,
# },
# )
# # Configuration for Ontology
# Ontology: CoinConf = CoinConf(
# coin_name=CoinNames("Ontology", "ONT"),
# params={
# "addr_ver": b"\x17",
# },
# )
# # Configuration for Optimism
# Optimism: CoinConf = CoinConf(
# coin_name=CoinNames("Optimism", "OP"),
# params={},
# )
# # Configuration for Osmosis
# Osmosis: CoinConf = CoinConf(
# coin_name=CoinNames("Osmosis", "OSMO"),
# params={
# "addr_hrp": Slip173.OSMOSIS,
# },
# )
# # Configuration for Phala
# Phala: CoinConf = CoinConf(
# coin_name=CoinNames("Phala Network", "PHA"),
# params={
# "addr_ss58_format": 30,
# },
# )
# # Configuration for Pi Network
# PiNetwork: CoinConf = CoinConf(
# coin_name=CoinNames("Pi Network", "PI"),
# params={},
# )
# # Configuration for Plasm
# Plasm: CoinConf = CoinConf(
# coin_name=CoinNames("Plasm Network", "PLM"),
# params={
# "addr_ss58_format": 5,
# },
# )
# # Configuration for Polkadot
# Polkadot: CoinConf = CoinConf(
# coin_name=CoinNames("Polkadot", "DOT"),
# params={
# "addr_ss58_format": 0,
# },
# )
# # Configuration for Polygon
# Polygon: CoinConf = CoinConf(
# coin_name=CoinNames("Polygon", "MATIC"),
# params={},
# )
# # Configuration for Ripple
# Ripple: CoinConf = CoinConf(
# coin_name=CoinNames("Ripple", "XRP"),
# params={
# "p2pkh_net_ver": _BTC_P2PKH_NET_VER_MN,
# },
# )
# # Configuration for Secret Network
# SecretNetwork: CoinConf = CoinConf(
# coin_name=CoinNames("Secret Network", "SCRT"),
# params={
# "addr_hrp": Slip173.SECRET_NETWORK,
# },
# )
# # Configuration for Solana
# Solana: CoinConf = CoinConf(
# coin_name=CoinNames("Solana", "SOL"),
# params={},
# )
# # Configuration for Sora
# Sora: CoinConf = CoinConf(
# coin_name=CoinNames("Sora", "XOR"),
# params={
# "addr_ss58_format": 69,
# },
# )
# # Configuration for Stafi
# Stafi: CoinConf = CoinConf(
# coin_name=CoinNames("Stafi", "FIS"),
# params={
# "addr_hrp": Slip173.STAFI,
# "addr_ss58_format": 20,
# },
# )
# # Configuration for Stellar
# Stellar: CoinConf = CoinConf(
# coin_name=CoinNames("Stellar", "XLM"),
# params={},
# )
# # Configuration for Sui
# Sui: CoinConf = CoinConf(
# coin_name=CoinNames("Sui", "SUI"),
# params={
# "addr_prefix": "0x",
# },
# )
# # Configuration for Terra
# Terra: CoinConf = CoinConf(
# coin_name=CoinNames("Terra", "LUNA"),
# params={
# "addr_hrp": Slip173.TERRA,
# },
# )
# # Configuration for Tezos
# Tezos: CoinConf = CoinConf(
# coin_name=CoinNames("Tezos", "XTZ"),
# params={},
# )
# # Configuration for Theta
# Theta: CoinConf = CoinConf(
# coin_name=CoinNames("Theta Network", "THETA"),
# params={},
# )
# # Configuration for Tron
# Tron: CoinConf = CoinConf(
# coin_name=CoinNames("Tron", "TRX"),
# params={
# "addr_prefix": b"\x41",
# },
# )
# # Configuration for VeChain
# VeChain: CoinConf = CoinConf(
# coin_name=CoinNames("VeChain", "VET"),
# params={},
# )
# # Configuration for Verge
# Verge: CoinConf = CoinConf(
# coin_name=CoinNames("Verge", "XVG"),
# params={
# "p2pkh_net_ver": b"\x1e",
# "wif_net_ver": b"\x9e",
# },
# )
# # Configuration for Zcash main net
# ZcashMainNet: CoinConf = CoinConf(
# coin_name=CoinNames("Zcash", "ZEC"),
# params={
# "p2pkh_net_ver": b"\x1c\xb8",
# "p2sh_net_ver": b"\x1c\xbd",
# "wif_net_ver": _BTC_WIF_NET_VER_MN,
# },
# )
# # Configuration for Zcash test net
# ZcashTestNet: CoinConf = CoinConf(
# coin_name=CoinNames("Zcash TestNet", "ZEC"),
# params={
# "p2pkh_net_ver": b"\x1d\x25",
# "p2sh_net_ver": b"\x1c\xba",
# "wif_net_ver": _BTC_WIF_NET_VER_TN,
# },
# )
# # Configuration for Zilliqa
# Zilliqa: CoinConf = CoinConf(
# coin_name=CoinNames("Zilliqa", "ZIL"),
# params={
# "addr_hrp": Slip173.ZILLIQA,
# },
# )
# For compatibility
# CoinsConf.Neo = CoinsConf.NeoLegacy
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/coin_conf/coins_conf.py",
"license": "MIT License",
"lines": 785,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip44/bip44_coins.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP44 coins enum."""
# Imports
from enum import auto, unique
from ..common.bip_coins import BipCoins
@unique
class Bip44Coins(BipCoins):
"""Enumerative for supported BIP44 coins."""
# Main nets
AKASH_NETWORK = auto()
ALGORAND = auto()
APTOS = auto()
ARBITRUM = auto()
AVAX_C_CHAIN = auto()
AVAX_P_CHAIN = auto()
AVAX_X_CHAIN = auto()
AXELAR = auto()
BAND_PROTOCOL = auto()
BINANCE_CHAIN = auto()
BINANCE_SMART_CHAIN = auto()
BITCOIN = auto()
BITCOIN_CASH = auto()
BITCOIN_CASH_SLP = auto()
BITCOIN_SV = auto()
CARDANO_BYRON_ICARUS = auto()
CARDANO_BYRON_LEDGER = auto()
CELESTIA = auto()
CELO = auto()
CERTIK = auto()
CHIHUAHUA = auto()
COSMOS = auto()
DASH = auto()
DOGECOIN = auto()
DYDX = auto()
ECASH = auto()
ELROND = auto()
EOS = auto()
ERGO = auto()
ETHEREUM = auto()
ETHEREUM_CLASSIC = auto()
FANTOM_OPERA = auto()
FETCH_AI = auto()
FETCH_AI_ETH = auto()
FILECOIN = auto()
HARMONY_ONE_ATOM = auto()
HARMONY_ONE_ETH = auto()
HARMONY_ONE_METAMASK = auto()
HUOBI_CHAIN = auto()
ICON = auto()
INJECTIVE = auto()
IRIS_NET = auto()
KAVA = auto()
KUSAMA_ED25519_SLIP = auto()
LITECOIN = auto()
METIS = auto()
MONERO_ED25519_SLIP = auto()
MONERO_SECP256K1 = auto()
MULTIVERSX = auto()
NANO = auto()
NEAR_PROTOCOL = auto()
NEO = auto()
NEO_LEGACY = auto()
NEO_N3 = auto()
NEUTRON = auto()
NIMIQ = auto()
NINE_CHRONICLES_GOLD = auto()
OKEX_CHAIN_ATOM = auto()
OKEX_CHAIN_ATOM_OLD = auto()
OKEX_CHAIN_ETH = auto()
ONTOLOGY = auto()
OPTIMISM = auto()
OSMOSIS = auto()
PI_NETWORK = auto()
POLKADOT_ED25519_SLIP = auto()
POLYGON = auto()
RIPPLE = auto()
SECRET_NETWORK_OLD = auto()
SECRET_NETWORK_NEW = auto()
SOLANA = auto()
STAFI = auto()
STELLAR = auto()
SUI = auto()
TERRA = auto()
TEZOS = auto()
THETA = auto()
TRON = auto()
VECHAIN = auto()
VERGE = auto()
ZCASH = auto()
ZILLIQA = auto()
# Test nets
BITCOIN_CASH_TESTNET = auto()
BITCOIN_CASH_SLP_TESTNET = auto()
BITCOIN_SV_TESTNET = auto()
BITCOIN_REGTEST = auto()
BITCOIN_TESTNET = auto()
DASH_TESTNET = auto()
DOGECOIN_TESTNET = auto()
ECASH_TESTNET = auto()
ERGO_TESTNET = auto()
LITECOIN_TESTNET = auto()
ZCASH_TESTNET = auto()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip44/bip44_coins.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip44/bip44_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP44 coins configuration."""
# Imports
from ..addr import (
AdaByronIcarusAddrEncoder, AlgoAddrEncoder, AptosAddrEncoder, AtomAddrEncoder, AvaxPChainAddrEncoder,
AvaxXChainAddrEncoder, BchP2PKHAddrEncoder, EgldAddrEncoder, EosAddrEncoder, ErgoNetworkTypes, ErgoP2PKHAddrEncoder,
EthAddrEncoder, FilSecp256k1AddrEncoder, IcxAddrEncoder, InjAddrEncoder, NanoAddrEncoder, NearAddrEncoder,
NeoLegacyAddrEncoder, NeoN3AddrEncoder, NimAddrEncoder, OkexAddrEncoder, OneAddrEncoder, P2PKHAddrEncoder,
SolAddrEncoder, SubstrateEd25519AddrEncoder, SuiAddrEncoder, TrxAddrEncoder, XlmAddrEncoder, XlmAddrTypes,
XmrAddrEncoder, XrpAddrEncoder, XtzAddrEncoder, XtzAddrPrefixes, ZilAddrEncoder
)
from ..bip32 import (
Bip32Const, Bip32KeyNetVersions, Bip32Slip10Ed25519, Bip32Slip10Ed25519Blake2b,
Bip32Slip10Nist256p1, Bip32Slip10Secp256k1
# Bip32KholawEd25519
)
# from import (
# DER_PATH_HARDENED_FULL, DER_PATH_HARDENED_MID, DER_PATH_HARDENED_SHORT, DER_PATH_NON_HARDENED_FULL,
# BipBitcoinCashConf, BipCoinConf, BipCoinFctCallsConf, BipLitecoinConf
# )
# from bip_utils.cardano.bip32.cardano_icarus_bip32 import CardanoIcarusBip32
from ..coin_conf import CoinsConf
from ..slip.slip44 import Slip44
# Bitcoin key net version for main net (same as BIP32)
_BIP44_BTC_KEY_NET_VER_MAIN: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS
# Bitcoin key net version for test net (same as BIP32)
_BIP44_BTC_KEY_NET_VER_TEST: Bip32KeyNetVersions = Bip32Const.TEST_NET_KEY_NET_VERSIONS
class Bip44Conf:
"""Class container for BIP44 configuration."""
# Configuration for Akash Network
AkashNetwork: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.AkashNetwork.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.AkashNetwork.ParamByKey("addr_hrp"),
},
)
# Configuration for Algorand
Algorand: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Algorand.CoinNames(),
coin_idx=Slip44.ALGORAND,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=AlgoAddrEncoder,
addr_params={},
)
# Configuration for Aptos
Aptos: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Aptos.CoinNames(),
coin_idx=Slip44.APTOS,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=AptosAddrEncoder,
addr_params={},
)
# Configuration for Arbitrum
Arbitrum: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Arbitrum.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Avax C-Chain
AvaxCChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.AvaxCChain.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Avax P-Chain
AvaxPChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.AvaxPChain.CoinNames(),
coin_idx=Slip44.AVALANCHE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AvaxPChainAddrEncoder,
addr_params={},
)
# Configuration for Avax X-Chain
AvaxXChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.AvaxXChain.CoinNames(),
coin_idx=Slip44.AVALANCHE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AvaxXChainAddrEncoder,
addr_params={},
)
# Configuration for Axelar
Axelar: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Axelar.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Axelar.ParamByKey("addr_hrp"),
},
)
# Configuration for Band Protocol
BandProtocol: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BandProtocol.CoinNames(),
coin_idx=Slip44.BAND_PROTOCOL,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.BandProtocol.ParamByKey("addr_hrp"),
},
)
# Configuration for Binance Chain
BinanceChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BinanceChain.CoinNames(),
coin_idx=Slip44.BINANCE_CHAIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.BinanceChain.ParamByKey("addr_hrp"),
},
)
# Configuration for Binance Smart Chain
BinanceSmartChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BinanceSmartChain.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Bitcoin main net
BitcoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinMainNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Bitcoin regtest
BitcoinRegTest: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinRegTest.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinRegTest.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinRegTest.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Bitcoin test net
BitcoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinTestNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Bitcoin Cash main net
BitcoinCashMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinCashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashMainNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashMainNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashMainNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for Bitcoin Cash test net
BitcoinCashTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinCashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashTestNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashTestNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashTestNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for Bitcoin Cash Simple Ledger Protocol main net
BitcoinCashSlpMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashSlpMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinCashSlpMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for Bitcoin Cash Simple Ledger Protocol test net
BitcoinCashSlpTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashSlpTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinCashSlpTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for BitcoinSV main net
BitcoinSvMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinSvMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_SV,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinSvMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinSvMainNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for BitcoinSV test net
BitcoinSvTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinSvTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinSvTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinSvTestNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Cardano Byron (Icarus)
# CardanoByronIcarus: BipCoinConf = BipCoinConf(
# coin_names=CoinsConf.CardanoMainNet.CoinNames(),
# coin_idx=Slip44.CARDANO,
# is_testnet=False,
# def_path=DER_PATH_NON_HARDENED_FULL,
# key_net_ver=Bip32Const.KHOLAW_KEY_NET_VERSIONS,
# wif_net_ver=None,
# bip32_cls=CardanoIcarusBip32,
# addr_cls=AdaByronIcarusAddrEncoder,
# addr_params={
# "chain_code": BipCoinFctCallsConf("ChainCode"),
# },
# )
# Configuration for Cardano Byron (Ledger)
CardanoByronLedger: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.CardanoMainNet.CoinNames(),
coin_idx=Slip44.CARDANO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32Const.KHOLAW_KEY_NET_VERSIONS,
wif_net_ver=None,
bip32_cls=Bip32KholawEd25519,
addr_cls=AdaByronIcarusAddrEncoder,
addr_params={
"chain_code": BipCoinFctCallsConf("ChainCode"),
},
)
# Configuration for Celestia
Celestia: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Celestia.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Celestia.ParamByKey("addr_hrp"),
},
)
# Configuration for Celo
Celo: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Celo.CoinNames(),
coin_idx=Slip44.CELO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Certik
Certik: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Certik.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Certik.ParamByKey("addr_hrp"),
},
)
# Configuration for Chihuahua
Chihuahua: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Chihuahua.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Chihuahua.ParamByKey("addr_hrp"),
},
)
# Configuration for Cosmos
Cosmos: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Cosmos.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Cosmos.ParamByKey("addr_hrp"),
},
)
# Configuration for Dash main net
DashMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DashMainNet.CoinNames(),
coin_idx=Slip44.DASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.DashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DashMainNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Dash test net
DashTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.DashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DashTestNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Dogecoin main net
DogecoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DogecoinMainNet.CoinNames(),
coin_idx=Slip44.DOGECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x02\xfa\xca\xfd",
b"\x02\xfa\xc3\x98"), # dgub / dgpv
wif_net_ver=CoinsConf.DogecoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DogecoinMainNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Dogecoin test net
DogecoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DogecoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x04\x32\xa9\xa8",
b"\x04\x32\xa2\x43"), # tgub / tgpv
wif_net_ver=CoinsConf.DogecoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DogecoinTestNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for dYdX
DYDX: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DYDX.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.DYDX.ParamByKey("addr_hrp"),
},
)
# Configuration for eCash main net
EcashMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.EcashMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.EcashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.EcashMainNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.EcashMainNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.EcashMainNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for eCash test net
EcashTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.EcashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.EcashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2PKHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.EcashTestNet.ParamByKey("p2pkh_std_net_ver"),
"hrp": CoinsConf.EcashTestNet.ParamByKey("p2pkh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.EcashTestNet.ParamByKey("p2pkh_legacy_net_ver"),
}
},
addr_cls_legacy=P2PKHAddrEncoder,
)
# Configuration for Elrond
Elrond: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Elrond.CoinNames(),
coin_idx=Slip44.ELROND,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=EgldAddrEncoder,
addr_params={},
)
# Configuration for Eos
Eos: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Eos.CoinNames(),
coin_idx=Slip44.EOS,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EosAddrEncoder,
addr_params={},
)
# Configuration for Ergo main net
ErgoMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ErgoMainNet.CoinNames(),
coin_idx=Slip44.ERGO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=ErgoP2PKHAddrEncoder,
addr_params={
"net_type": ErgoNetworkTypes.MAINNET,
},
)
# Configuration for Ergo test net
ErgoTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ErgoTestNet.CoinNames(),
coin_idx=Slip44.ERGO,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=ErgoP2PKHAddrEncoder,
addr_params={
"net_type": ErgoNetworkTypes.TESTNET,
},
)
# Configuration for Ethereum
Ethereum: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Ethereum.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Ethereum Classic
EthereumClassic: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.EthereumClassic.CoinNames(),
coin_idx=Slip44.ETHEREUM_CLASSIC,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Fantom Opera
FantomOpera: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.FantomOpera.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Fetch.ai
FetchAi: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.FetchAi.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.FetchAi.ParamByKey("addr_hrp"),
},
)
# Configuration for Fetch.ai (ETH)
FetchAiEth: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.FetchAi.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.FetchAi.ParamByKey("addr_hrp"),
},
)
# Configuration for Filecoin
Filecoin: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Filecoin.CoinNames(),
coin_idx=Slip44.FILECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=FilSecp256k1AddrEncoder,
addr_params={},
)
# Configuration for Harmony One (Metamask address)
HarmonyOneMetamask: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.HarmonyOne.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Harmony One (Ethereum address)
HarmonyOneEth: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.HarmonyOne.CoinNames(),
coin_idx=Slip44.HARMONY_ONE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Harmony One (Atom address)
HarmonyOneAtom: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.HarmonyOne.CoinNames(),
coin_idx=Slip44.HARMONY_ONE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=OneAddrEncoder,
addr_params={},
)
# Configuration for Huobi Chain
HuobiChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.HuobiChain.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Icon
Icon: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Icon.CoinNames(),
coin_idx=Slip44.ICON,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=IcxAddrEncoder,
addr_params={},
)
# Configuration for Injective
Injective: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Injective.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=InjAddrEncoder,
addr_params={},
)
# Configuration for IRISnet
IrisNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.IrisNet.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.IrisNet.ParamByKey("addr_hrp"),
},
)
# Configuration for Kava
Kava: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Kava.CoinNames(),
coin_idx=Slip44.KAVA,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Kava.ParamByKey("addr_hrp"),
},
)
# Configuration for Kusama (ed25519 SLIP-0010)
KusamaEd25519Slip: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Kusama.CoinNames(),
coin_idx=Slip44.KUSAMA,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=SubstrateEd25519AddrEncoder,
addr_params={
"ss58_format": CoinsConf.Kusama.ParamByKey("addr_ss58_format"),
},
)
# Configuration for Litecoin main net
LitecoinMainNet: BipLitecoinConf = BipLitecoinConf(
coin_names=CoinsConf.LitecoinMainNet.CoinNames(),
coin_idx=Slip44.LITECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
alt_key_net_ver=Bip32KeyNetVersions(b"\x01\x9d\xa4\x62",
b"\x01\x9d\x9c\xfe"), # Ltpv / Ltub
wif_net_ver=CoinsConf.LitecoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"std_net_ver": CoinsConf.LitecoinMainNet.ParamByKey("p2pkh_std_net_ver"),
"depr_net_ver": CoinsConf.LitecoinMainNet.ParamByKey("p2pkh_depr_net_ver"),
},
)
# Configuration for Litecoin test net
LitecoinTestNet: BipLitecoinConf = BipLitecoinConf(
coin_names=CoinsConf.LitecoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x04\x36\xf6\xe1",
b"\x04\x36\xef\x7d"), # ttub / ttpv
alt_key_net_ver=Bip32KeyNetVersions(b"\x04\x36\xf6\xe1",
b"\x04\x36\xef\x7d"), # ttub / ttpv
wif_net_ver=CoinsConf.LitecoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"std_net_ver": CoinsConf.LitecoinTestNet.ParamByKey("p2pkh_std_net_ver"),
"depr_net_ver": CoinsConf.LitecoinTestNet.ParamByKey("p2pkh_depr_net_ver"),
},
)
# Configuration for Metis
Metis: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Metis.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Monero (ed25519 SLIP-0010)
MoneroEd25519Slip: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.MoneroMainNet.CoinNames(),
coin_idx=Slip44.MONERO,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=XmrAddrEncoder,
addr_params={},
)
# Configuration for Monero (secp256k1)
MoneroSecp256k1: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.MoneroMainNet.CoinNames(),
coin_idx=Slip44.MONERO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=XmrAddrEncoder,
addr_params={},
)
# Configuration for Nano
Nano: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Nano.CoinNames(),
coin_idx=Slip44.NANO,
is_testnet=False,
def_path=DER_PATH_HARDENED_SHORT,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519Blake2b,
addr_cls=NanoAddrEncoder,
addr_params={},
)
# Configuration for Near Protocol
NearProtocol: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.NearProtocol.CoinNames(),
coin_idx=Slip44.NEAR_PROTOCOL,
is_testnet=False,
def_path=DER_PATH_HARDENED_SHORT,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=NearAddrEncoder,
addr_params={},
)
# For compatibility, later assigned to NeoLegacy
Neo: BipCoinConf
# Configuration for Neo legacy
NeoLegacy: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.NeoLegacy.CoinNames(),
coin_idx=Slip44.NEO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.NeoLegacy.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Nist256p1,
addr_cls=NeoLegacyAddrEncoder,
addr_params={
"ver": CoinsConf.NeoLegacy.ParamByKey("addr_ver"),
},
)
# Configuration for Neo N3
NeoN3: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.NeoN3.CoinNames(),
coin_idx=Slip44.NEO,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.NeoN3.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Nist256p1,
addr_cls=NeoN3AddrEncoder,
addr_params={
"ver": CoinsConf.NeoN3.ParamByKey("addr_ver"),
},
)
# Configuration for Neutron
Neutron: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Neutron.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Neutron.ParamByKey("addr_hrp"),
},
)
# Configuration for Nimiq
Nimiq: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Nimiq.CoinNames(),
coin_idx=Slip44.NIMIQ,
is_testnet=False,
def_path=DER_PATH_HARDENED_MID,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=NimAddrEncoder,
addr_params={},
)
# Configuration for NG
NineChroniclesGold: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.NineChroniclesGold.CoinNames(),
coin_idx=Slip44.NINE_CHRONICLES,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for OKEx Chain (Ethereum address)
OkexChainEth: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.OkexChain.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for OKEx Chain (Atom address)
OkexChainAtom: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.OkexChain.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=OkexAddrEncoder,
addr_params={},
)
# Configuration for OKEx Chain (old Atom address)
OkexChainAtomOld: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.OkexChain.CoinNames(),
coin_idx=Slip44.OKEX_CHAIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=OkexAddrEncoder,
addr_params={},
)
# Configuration for Ontology
Ontology: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Ontology.CoinNames(),
coin_idx=Slip44.ONTOLOGY,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Nist256p1,
addr_cls=NeoLegacyAddrEncoder,
addr_params={
"ver": CoinsConf.Ontology.ParamByKey("addr_ver"),
},
)
# Configuration for Optimism
Optimism: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Optimism.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Osmosis
Osmosis: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Osmosis.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Osmosis.ParamByKey("addr_hrp"),
},
)
# Configuration for Pi Network
PiNetwork: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.PiNetwork.CoinNames(),
coin_idx=Slip44.PI_NETWORK,
is_testnet=False,
def_path=DER_PATH_HARDENED_SHORT,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=XlmAddrEncoder,
addr_params={"addr_type": XlmAddrTypes.PUB_KEY},
)
# Configuration for Polkadot (ed25519 SLIP-0010)
PolkadotEd25519Slip: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Polkadot.CoinNames(),
coin_idx=Slip44.POLKADOT,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=SubstrateEd25519AddrEncoder,
addr_params={
"ss58_format": CoinsConf.Polkadot.ParamByKey("addr_ss58_format"),
},
)
# Configuration for Polygon
Polygon: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Polygon.CoinNames(),
coin_idx=Slip44.ETHEREUM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Ripple
Ripple: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Ripple.CoinNames(),
coin_idx=Slip44.RIPPLE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=XrpAddrEncoder,
addr_params={},
)
# Configuration for Secret Network (old path)
SecretNetworkOld: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.SecretNetwork.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.SecretNetwork.ParamByKey("addr_hrp"),
},
)
# Configuration for Secret Network (new path)
SecretNetworkNew: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.SecretNetwork.CoinNames(),
coin_idx=Slip44.SECRET_NETWORK,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.SecretNetwork.ParamByKey("addr_hrp"),
},
)
# Configuration for Solana
Solana: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Solana.CoinNames(),
coin_idx=Slip44.SOLANA,
is_testnet=False,
def_path=DER_PATH_HARDENED_SHORT,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=SolAddrEncoder,
addr_params={},
)
# Configuration for Stafi
Stafi: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Stafi.CoinNames(),
coin_idx=Slip44.ATOM,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Stafi.ParamByKey("addr_hrp"),
},
)
# Configuration for Stellar
Stellar: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Stellar.CoinNames(),
coin_idx=Slip44.STELLAR,
is_testnet=False,
def_path=DER_PATH_HARDENED_SHORT,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=XlmAddrEncoder,
addr_params={"addr_type": XlmAddrTypes.PUB_KEY},
)
# Configuration for Sui
Sui: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Sui.CoinNames(),
coin_idx=Slip44.SUI,
is_testnet=False,
def_path=DER_PATH_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=SuiAddrEncoder,
addr_params={},
)
# Configuration for Terra
Terra: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Terra.CoinNames(),
coin_idx=Slip44.TERRA,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=AtomAddrEncoder,
addr_params={
"hrp": CoinsConf.Terra.ParamByKey("addr_hrp"),
},
)
# Configuration for Tezos
Tezos: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Tezos.CoinNames(),
coin_idx=Slip44.TEZOS,
is_testnet=False,
def_path=DER_PATH_HARDENED_MID,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Ed25519,
addr_cls=XtzAddrEncoder,
addr_params={"prefix": XtzAddrPrefixes.TZ1},
)
# Configuration for Theta
Theta: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Theta.CoinNames(),
coin_idx=Slip44.THETA,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Tron
Tron: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Tron.CoinNames(),
coin_idx=Slip44.TRON,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=TrxAddrEncoder,
addr_params={},
)
# Configuration for VeChain
VeChain: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.VeChain.CoinNames(),
coin_idx=Slip44.VECHAIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=EthAddrEncoder,
addr_params={},
)
# Configuration for Verge
Verge: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Verge.CoinNames(),
coin_idx=Slip44.VERGE,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.Verge.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.Verge.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Zcash main net
ZcashMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ZcashMainNet.CoinNames(),
coin_idx=Slip44.ZCASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.ZcashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.ZcashMainNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Zcash test net
ZcashTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ZcashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.ZcashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2PKHAddrEncoder,
addr_params={
"net_ver": CoinsConf.ZcashTestNet.ParamByKey("p2pkh_net_ver"),
},
)
# Configuration for Zilliqa
Zilliqa: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.Zilliqa.CoinNames(),
coin_idx=Slip44.ZILLIQA,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP44_BTC_KEY_NET_VER_MAIN,
wif_net_ver=None,
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=ZilAddrEncoder,
addr_params={},
)
# For compatibility
Bip44Conf.Neo = Bip44Conf.NeoLegacy
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip44/bip44_conf.py",
"license": "MIT License",
"lines": 1278,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip44/bip44_conf_getter.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for getting BIP44 coins configuration."""
# Imports
from typing import Dict
from bip_utils.bip.conf.bip44.bip44_coins import Bip44Coins
from bip_utils.bip.conf.bip44.bip44_conf import Bip44Conf
from import BipCoinConf, BipCoins
class Bip44ConfGetterConst:
"""Class container for BIP44 configuration getter constants."""
# Map from Bip44Coins to configuration classes
COIN_TO_CONF: Dict[BipCoins, BipCoinConf] = {
Bip44Coins.AKASH_NETWORK: Bip44Conf.AkashNetwork,
Bip44Coins.ALGORAND: Bip44Conf.Algorand,
Bip44Coins.APTOS: Bip44Conf.Aptos,
Bip44Coins.ARBITRUM: Bip44Conf.Arbitrum,
Bip44Coins.AVAX_C_CHAIN: Bip44Conf.AvaxCChain,
Bip44Coins.AVAX_P_CHAIN: Bip44Conf.AvaxPChain,
Bip44Coins.AVAX_X_CHAIN: Bip44Conf.AvaxXChain,
Bip44Coins.AXELAR: Bip44Conf.Axelar,
Bip44Coins.BAND_PROTOCOL: Bip44Conf.BandProtocol,
Bip44Coins.BINANCE_CHAIN: Bip44Conf.BinanceChain,
Bip44Coins.BINANCE_SMART_CHAIN: Bip44Conf.BinanceSmartChain,
Bip44Coins.BITCOIN: Bip44Conf.BitcoinMainNet,
Bip44Coins.BITCOIN_REGTEST: Bip44Conf.BitcoinRegTest,
Bip44Coins.BITCOIN_TESTNET: Bip44Conf.BitcoinTestNet,
Bip44Coins.BITCOIN_CASH: Bip44Conf.BitcoinCashMainNet,
Bip44Coins.BITCOIN_CASH_TESTNET: Bip44Conf.BitcoinCashTestNet,
Bip44Coins.BITCOIN_CASH_SLP: Bip44Conf.BitcoinCashSlpMainNet,
Bip44Coins.BITCOIN_CASH_SLP_TESTNET: Bip44Conf.BitcoinCashSlpTestNet,
Bip44Coins.BITCOIN_SV: Bip44Conf.BitcoinSvMainNet,
Bip44Coins.BITCOIN_SV_TESTNET: Bip44Conf.BitcoinSvTestNet,
Bip44Coins.CARDANO_BYRON_ICARUS: Bip44Conf.CardanoByronIcarus,
Bip44Coins.CARDANO_BYRON_LEDGER: Bip44Conf.CardanoByronLedger,
Bip44Coins.CELESTIA: Bip44Conf.Celestia,
Bip44Coins.CELO: Bip44Conf.Celo,
Bip44Coins.CERTIK: Bip44Conf.Certik,
Bip44Coins.CHIHUAHUA: Bip44Conf.Chihuahua,
Bip44Coins.COSMOS: Bip44Conf.Cosmos,
Bip44Coins.DASH: Bip44Conf.DashMainNet,
Bip44Coins.DASH_TESTNET: Bip44Conf.DashTestNet,
Bip44Coins.DOGECOIN: Bip44Conf.DogecoinMainNet,
Bip44Coins.DOGECOIN_TESTNET: Bip44Conf.DogecoinTestNet,
Bip44Coins.DYDX: Bip44Conf.DYDX,
Bip44Coins.ECASH: Bip44Conf.EcashMainNet,
Bip44Coins.ECASH_TESTNET: Bip44Conf.EcashTestNet,
Bip44Coins.ELROND: Bip44Conf.Elrond,
Bip44Coins.EOS: Bip44Conf.Eos,
Bip44Coins.ERGO: Bip44Conf.ErgoMainNet,
Bip44Coins.ERGO_TESTNET: Bip44Conf.ErgoTestNet,
Bip44Coins.ETHEREUM: Bip44Conf.Ethereum,
Bip44Coins.ETHEREUM_CLASSIC: Bip44Conf.EthereumClassic,
Bip44Coins.FANTOM_OPERA: Bip44Conf.FantomOpera,
Bip44Coins.FETCH_AI: Bip44Conf.FetchAi,
Bip44Coins.FETCH_AI_ETH: Bip44Conf.FetchAiEth,
Bip44Coins.FILECOIN: Bip44Conf.Filecoin,
Bip44Coins.HARMONY_ONE_ATOM: Bip44Conf.HarmonyOneAtom,
Bip44Coins.HARMONY_ONE_ETH: Bip44Conf.HarmonyOneEth,
Bip44Coins.HARMONY_ONE_METAMASK: Bip44Conf.HarmonyOneMetamask,
Bip44Coins.HUOBI_CHAIN: Bip44Conf.HuobiChain,
Bip44Coins.ICON: Bip44Conf.Icon,
Bip44Coins.INJECTIVE: Bip44Conf.Injective,
Bip44Coins.IRIS_NET: Bip44Conf.IrisNet,
Bip44Coins.KAVA: Bip44Conf.Kava,
Bip44Coins.KUSAMA_ED25519_SLIP: Bip44Conf.KusamaEd25519Slip,
Bip44Coins.LITECOIN: Bip44Conf.LitecoinMainNet,
Bip44Coins.LITECOIN_TESTNET: Bip44Conf.LitecoinTestNet,
Bip44Coins.METIS: Bip44Conf.Metis,
Bip44Coins.MONERO_ED25519_SLIP: Bip44Conf.MoneroEd25519Slip,
Bip44Coins.MONERO_SECP256K1: Bip44Conf.MoneroSecp256k1,
Bip44Coins.MULTIVERSX: Bip44Conf.Elrond,
Bip44Coins.NANO: Bip44Conf.Nano,
Bip44Coins.NEAR_PROTOCOL: Bip44Conf.NearProtocol,
Bip44Coins.NEO: Bip44Conf.NeoLegacy,
Bip44Coins.NEO_LEGACY: Bip44Conf.NeoLegacy,
Bip44Coins.NEO_N3: Bip44Conf.NeoN3,
Bip44Coins.NEUTRON: Bip44Conf.Neutron,
Bip44Coins.NIMIQ: Bip44Conf.Nimiq,
Bip44Coins.NINE_CHRONICLES_GOLD: Bip44Conf.NineChroniclesGold,
Bip44Coins.OKEX_CHAIN_ATOM: Bip44Conf.OkexChainAtom,
Bip44Coins.OKEX_CHAIN_ATOM_OLD: Bip44Conf.OkexChainAtomOld,
Bip44Coins.OKEX_CHAIN_ETH: Bip44Conf.OkexChainEth,
Bip44Coins.ONTOLOGY: Bip44Conf.Ontology,
Bip44Coins.OPTIMISM: Bip44Conf.Optimism,
Bip44Coins.OSMOSIS: Bip44Conf.Osmosis,
Bip44Coins.PI_NETWORK: Bip44Conf.PiNetwork,
Bip44Coins.POLKADOT_ED25519_SLIP: Bip44Conf.PolkadotEd25519Slip,
Bip44Coins.POLYGON: Bip44Conf.Polygon,
Bip44Coins.RIPPLE: Bip44Conf.Ripple,
Bip44Coins.SECRET_NETWORK_OLD: Bip44Conf.SecretNetworkOld,
Bip44Coins.SECRET_NETWORK_NEW: Bip44Conf.SecretNetworkNew,
Bip44Coins.SOLANA: Bip44Conf.Solana,
Bip44Coins.STAFI: Bip44Conf.Stafi,
Bip44Coins.STELLAR: Bip44Conf.Stellar,
Bip44Coins.SUI: Bip44Conf.Sui,
Bip44Coins.TERRA: Bip44Conf.Terra,
Bip44Coins.TEZOS: Bip44Conf.Tezos,
Bip44Coins.THETA: Bip44Conf.Theta,
Bip44Coins.TRON: Bip44Conf.Tron,
Bip44Coins.VECHAIN: Bip44Conf.VeChain,
Bip44Coins.VERGE: Bip44Conf.Verge,
Bip44Coins.ZCASH: Bip44Conf.ZcashMainNet,
Bip44Coins.ZCASH_TESTNET: Bip44Conf.ZcashTestNet,
Bip44Coins.ZILLIQA: Bip44Conf.Zilliqa,
}
class Bip44ConfGetter:
"""
BIP44 configuration getter class.
It allows to get the BIP44 configuration of a specific coin.
"""
@staticmethod
def GetConfig(coin_type: BipCoins) -> BipCoinConf:
"""
Get coin configuration.
Args:
coin_type (BipCoins): Coin type
Returns:
BipCoinConf: Coin configuration
Raises:
TypeError: If coin type is not of a Bip44Coins enumerative
"""
if not isinstance(coin_type, Bip44Coins):
raise TypeError("Coin type is not an enumerative of Bip44Coins")
return Bip44ConfGetterConst.COIN_TO_CONF[coin_type]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip44/bip44_conf_getter.py",
"license": "MIT License",
"lines": 141,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip49/bip49_coins.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP49 coins enum."""
# Imports
from enum import auto, unique
from .bip_coins import BipCoins
@unique
class Bip49Coins(BipCoins):
"""Enumerative for supported BIP49 coins."""
# Main nets
BITCOIN = auto()
BITCOIN_CASH = auto()
BITCOIN_CASH_SLP = auto()
BITCOIN_SV = auto()
DASH = auto()
DOGECOIN = auto()
ECASH = auto()
LITECOIN = auto()
ZCASH = auto()
# Test nets
BITCOIN_CASH_TESTNET = auto()
BITCOIN_CASH_SLP_TESTNET = auto()
BITCOIN_SV_TESTNET = auto()
BITCOIN_REGTEST = auto()
BITCOIN_TESTNET = auto()
DASH_TESTNET = auto()
DOGECOIN_TESTNET = auto()
ECASH_TESTNET = auto()
LITECOIN_TESTNET = auto()
ZCASH_TESTNET = auto()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip49/bip49_coins.py",
"license": "MIT License",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip49/bip49_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP49 coins configuration."""
# Imports
from bip_utils.addr import BchP2SHAddrEncoder, P2SHAddrEncoder
from bip_utils.bip.bip32 import Bip32KeyNetVersions, Bip32Slip10Secp256k1
from import DER_PATH_NON_HARDENED_FULL, BipBitcoinCashConf, BipCoinConf, BipLitecoinConf
from bip_utils.coin_conf import CoinsConf
from bip_utils.slip.slip44 import Slip44
# Bitcoin key net version for main net (ypub / yprv)
_BIP49_BTC_KEY_NET_VER_MAIN: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x9d\x7c\xb2",
b"\x04\x9d\x78\x78")
# Bitcoin key net version for test net (upub / uprv)
_BIP49_BTC_KEY_NET_VER_TEST: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x4a\x52\x62",
b"\x04\x4a\x4e\x28")
class Bip49Conf:
"""Class container for BIP49 configuration."""
# Configuration for Bitcoin main net
BitcoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinMainNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Bitcoin regtest
BitcoinRegTest: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinRegTest.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinRegTest.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinRegTest.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Bitcoin test net
BitcoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinTestNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Bitcoin Cash main net
BitcoinCashMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinCashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashMainNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashMainNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashMainNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for Bitcoin Cash test net
BitcoinCashTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinCashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashTestNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashTestNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashTestNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for Bitcoin Cash Simple Ledger Protocol main net
BitcoinCashSlpMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashSlpMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinCashSlpMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashSlpMainNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for Bitcoin Cash Simple Ledger Protocol test net
BitcoinCashSlpTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.BitcoinCashSlpTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinCashSlpTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.BitcoinCashSlpTestNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for BitcoinSV main net
BitcoinSvMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinSvMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_SV,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinSvMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinSvMainNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for BitcoinSV test net
BitcoinSvTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinSvTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinSvTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.BitcoinSvTestNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Dash main net
DashMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DashMainNet.CoinNames(),
coin_idx=Slip44.DASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.DashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DashMainNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Dash test net
DashTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.DashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DashTestNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Dogecoin main net
DogecoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DogecoinMainNet.CoinNames(),
coin_idx=Slip44.DOGECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x02\xfa\xca\xfd",
b"\x02\xfa\xc3\x98"), # dgub / dgpv
wif_net_ver=CoinsConf.DogecoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DogecoinMainNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Dogecoin test net
DogecoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.DogecoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x04\x32\xa9\xa8",
b"\x04\x32\xa2\x43"), # tgub / tgpv
wif_net_ver=CoinsConf.DogecoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.DogecoinTestNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for eCash main net
EcashMainNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.EcashMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN_CASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.EcashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.EcashMainNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.EcashMainNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.EcashMainNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for eCash test net
EcashTestNet: BipBitcoinCashConf = BipBitcoinCashConf(
coin_names=CoinsConf.EcashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.EcashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=BchP2SHAddrEncoder,
addr_params={
"std": {
"net_ver": CoinsConf.EcashTestNet.ParamByKey("p2sh_std_net_ver"),
"hrp": CoinsConf.EcashTestNet.ParamByKey("p2sh_std_hrp"),
},
"legacy": {
"net_ver": CoinsConf.EcashTestNet.ParamByKey("p2sh_legacy_net_ver"),
}
},
addr_cls_legacy=P2SHAddrEncoder,
)
# Configuration for Litecoin main net
LitecoinMainNet: BipLitecoinConf = BipLitecoinConf(
coin_names=CoinsConf.LitecoinMainNet.CoinNames(),
coin_idx=Slip44.LITECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
alt_key_net_ver=Bip32KeyNetVersions(b"\x01\xb2\x6e\xf6",
b"\x01\xb2\x67\x92"), # Mtpv / Mtub
wif_net_ver=CoinsConf.LitecoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"std_net_ver": CoinsConf.LitecoinMainNet.ParamByKey("p2sh_std_net_ver"),
"depr_net_ver": CoinsConf.LitecoinMainNet.ParamByKey("p2sh_depr_net_ver"),
},
)
# Configuration for Litecoin test net
LitecoinTestNet: BipLitecoinConf = BipLitecoinConf(
coin_names=CoinsConf.LitecoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x04\x36\xf6\xe1",
b"\x04\x36\xef\x7d"), # ttub / ttpv
alt_key_net_ver=Bip32KeyNetVersions(b"\x04\x36\xf6\xe1",
b"\x04\x36\xef\x7d"), # ttub / ttpv
wif_net_ver=CoinsConf.LitecoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"std_net_ver": CoinsConf.LitecoinTestNet.ParamByKey("p2sh_std_net_ver"),
"depr_net_ver": CoinsConf.LitecoinTestNet.ParamByKey("p2sh_depr_net_ver"),
},
)
# Configuration for Zcash main net
ZcashMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ZcashMainNet.CoinNames(),
coin_idx=Slip44.ZCASH,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.ZcashMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.ZcashMainNet.ParamByKey("p2sh_net_ver"),
},
)
# Configuration for Zcash test net
ZcashTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.ZcashTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP49_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.ZcashTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2SHAddrEncoder,
addr_params={
"net_ver": CoinsConf.ZcashTestNet.ParamByKey("p2sh_net_ver"),
},
)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip49/bip49_conf.py",
"license": "MIT License",
"lines": 351,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip49/bip49_conf_getter.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for getting BIP49 coins configuration."""
# Imports
from typing import Dict
from bip_utils.bip.conf.bip49.bip49_coins import Bip49Coins
from bip_utils.bip.conf.bip49.bip49_conf import Bip49Conf
from import BipCoinConf, BipCoins
class Bip49ConfGetterConst:
"""Class container for BIP49 configuration getter constants."""
# Map from Bip49Coins to configuration classes
COIN_TO_CONF: Dict[BipCoins, BipCoinConf] = {
Bip49Coins.BITCOIN: Bip49Conf.BitcoinMainNet,
Bip49Coins.BITCOIN_REGTEST: Bip49Conf.BitcoinRegTest,
Bip49Coins.BITCOIN_TESTNET: Bip49Conf.BitcoinTestNet,
Bip49Coins.BITCOIN_CASH: Bip49Conf.BitcoinCashMainNet,
Bip49Coins.BITCOIN_CASH_TESTNET: Bip49Conf.BitcoinCashTestNet,
Bip49Coins.BITCOIN_CASH_SLP: Bip49Conf.BitcoinCashSlpMainNet,
Bip49Coins.BITCOIN_CASH_SLP_TESTNET: Bip49Conf.BitcoinCashSlpTestNet,
Bip49Coins.BITCOIN_SV: Bip49Conf.BitcoinSvMainNet,
Bip49Coins.BITCOIN_SV_TESTNET: Bip49Conf.BitcoinSvTestNet,
Bip49Coins.DASH: Bip49Conf.DashMainNet,
Bip49Coins.DASH_TESTNET: Bip49Conf.DashTestNet,
Bip49Coins.DOGECOIN: Bip49Conf.DogecoinMainNet,
Bip49Coins.DOGECOIN_TESTNET: Bip49Conf.DogecoinTestNet,
Bip49Coins.ECASH: Bip49Conf.EcashMainNet,
Bip49Coins.ECASH_TESTNET: Bip49Conf.EcashTestNet,
Bip49Coins.LITECOIN: Bip49Conf.LitecoinMainNet,
Bip49Coins.LITECOIN_TESTNET: Bip49Conf.LitecoinTestNet,
Bip49Coins.ZCASH: Bip49Conf.ZcashMainNet,
Bip49Coins.ZCASH_TESTNET: Bip49Conf.ZcashTestNet,
}
class Bip49ConfGetter:
"""
BIP49 configuration getter class.
It allows to get the BIP49 configuration of a specific coin.
"""
@staticmethod
def GetConfig(coin_type: BipCoins) -> BipCoinConf:
"""
Get coin configuration.
Args:
coin_type (BipCoins): Coin type
Returns:
BipCoinConf: Coin configuration
Raises:
TypeError: If coin type is not of a Bip49Coins enumerative
"""
if not isinstance(coin_type, Bip49Coins):
raise TypeError("Coin type is not an enumerative of Bip49Coins")
return Bip49ConfGetterConst.COIN_TO_CONF[coin_type]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip49/bip49_conf_getter.py",
"license": "MIT License",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip84/bip84_coins.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP84 coins enum."""
# Imports
from enum import auto, unique
from .bip_coins import BipCoins
@unique
class Bip84Coins(BipCoins):
"""Enumerative for supported BIP84 coins."""
# Main nets
BITCOIN = auto()
LITECOIN = auto()
# Test nets
BITCOIN_REGTEST = auto()
BITCOIN_TESTNET = auto()
LITECOIN_TESTNET = auto()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip84/bip84_coins.py",
"license": "MIT License",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip84/bip84_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP84 coins configuration."""
# Imports
from bip_utils.addr import P2WPKHAddrEncoder
from bip_utils.bip.bip32 import Bip32KeyNetVersions, Bip32Slip10Secp256k1
from import DER_PATH_NON_HARDENED_FULL, BipCoinConf
from bip_utils.coin_conf import CoinsConf
from bip_utils.slip.slip44 import Slip44
# Bitcoin key net version for main net (zpub / zprv)
_BIP84_BTC_KEY_NET_VER_MAIN: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\xb2\x47\x46",
b"\x04\xb2\x43\x0c")
# Bitcoin key test net version for test net (vpub / vprv)
_BIP84_BTC_KEY_NET_VER_TEST: Bip32KeyNetVersions = Bip32KeyNetVersions(b"\x04\x5f\x1c\xf6",
b"\x04\x5f\x18\xbc")
class Bip84Conf:
"""Class container for BIP84 configuration."""
# Configuration for Bitcoin main net
BitcoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP84_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2WPKHAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinMainNet.ParamByKey("p2wpkh_hrp"),
},
)
# Configuration for Bitcoin regtest
BitcoinRegTest: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinRegTest.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP84_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinRegTest.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2WPKHAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinRegTest.ParamByKey("p2wpkh_hrp"),
},
)
# Configuration for Bitcoin test net
BitcoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP84_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2WPKHAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinTestNet.ParamByKey("p2wpkh_hrp"),
},
)
# Configuration for Litecoin main net
LitecoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.LitecoinMainNet.CoinNames(),
coin_idx=Slip44.LITECOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP84_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.LitecoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2WPKHAddrEncoder,
addr_params={
"hrp": CoinsConf.LitecoinMainNet.ParamByKey("p2wpkh_hrp"),
},
)
# Configuration for Litecoin test net
LitecoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.LitecoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=Bip32KeyNetVersions(b"\x04\x36\xf6\xe1",
b"\x04\x36\xef\x7d"), # ttub / ttpv
wif_net_ver=CoinsConf.LitecoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2WPKHAddrEncoder,
addr_params={
"hrp": CoinsConf.LitecoinTestNet.ParamByKey("p2wpkh_hrp"),
},
)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip84/bip84_conf.py",
"license": "MIT License",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip84/bip84_conf_getter.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for getting BIP84 coins configuration."""
# Imports
from typing import Dict
from bip_utils.bip.conf.bip84.bip84_coins import Bip84Coins
from bip_utils.bip.conf.bip84.bip84_conf import Bip84Conf
from import BipCoinConf, BipCoins
class Bip84ConfGetterConst:
"""Class container for BIP84 configuration getter constants."""
# Map from Bip84Coins to configuration classes
COIN_TO_CONF: Dict[BipCoins, BipCoinConf] = {
Bip84Coins.BITCOIN: Bip84Conf.BitcoinMainNet,
Bip84Coins.BITCOIN_REGTEST: Bip84Conf.BitcoinRegTest,
Bip84Coins.BITCOIN_TESTNET: Bip84Conf.BitcoinTestNet,
Bip84Coins.LITECOIN: Bip84Conf.LitecoinMainNet,
Bip84Coins.LITECOIN_TESTNET: Bip84Conf.LitecoinTestNet,
}
class Bip84ConfGetter:
"""
BIP84 configuration getter class.
It allows to get the BIP84 configuration of a specific coin.
"""
@staticmethod
def GetConfig(coin_type: BipCoins) -> BipCoinConf:
"""
Get coin configuration.
Args:
coin_type (BipCoins): Coin type
Returns:
BipCoinConf: Coin configuration
Raises:
TypeError: If coin type is not of a Bip84Coins enumerative
"""
if not isinstance(coin_type, Bip84Coins):
raise TypeError("Coin type is not an enumerative of Bip84Coins")
return Bip84ConfGetterConst.COIN_TO_CONF[coin_type]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip84/bip84_conf_getter.py",
"license": "MIT License",
"lines": 54,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip86/bip86_coins.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP86 coins enum."""
# Imports
from enum import auto, unique
from .bip_coins import BipCoins
@unique
class Bip86Coins(BipCoins):
"""Enumerative for supported BIP86 coins."""
# Main nets
BITCOIN = auto()
# Test nets
BITCOIN_REGTEST = auto()
BITCOIN_TESTNET = auto()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip86/bip86_coins.py",
"license": "MIT License",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip86/bip86_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BIP86 coins configuration."""
# Imports
from bip_utils.addr import P2TRAddrEncoder
from bip_utils.bip.bip32 import Bip32Const, Bip32KeyNetVersions, Bip32Slip10Secp256k1
from import DER_PATH_NON_HARDENED_FULL, BipCoinConf
from bip_utils.coin_conf import CoinsConf
from bip_utils.slip.slip44 import Slip44
# Bitcoin key net version for main net (same as BIP32)
_BIP86_BTC_KEY_NET_VER_MAIN: Bip32KeyNetVersions = Bip32Const.MAIN_NET_KEY_NET_VERSIONS
# Bitcoin key net version for test net (same as BIP32)
_BIP86_BTC_KEY_NET_VER_TEST: Bip32KeyNetVersions = Bip32Const.TEST_NET_KEY_NET_VERSIONS
class Bip86Conf:
"""Class container for BIP86 configuration."""
# Configuration for Bitcoin main net
BitcoinMainNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinMainNet.CoinNames(),
coin_idx=Slip44.BITCOIN,
is_testnet=False,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP86_BTC_KEY_NET_VER_MAIN,
wif_net_ver=CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2TRAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinMainNet.ParamByKey("p2tr_hrp"),
},
)
# Configuration for Bitcoin regtest
BitcoinRegTest: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinRegTest.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP86_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinRegTest.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2TRAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinRegTest.ParamByKey("p2tr_hrp"),
},
)
# Configuration for Bitcoin test net
BitcoinTestNet: BipCoinConf = BipCoinConf(
coin_names=CoinsConf.BitcoinTestNet.CoinNames(),
coin_idx=Slip44.TESTNET,
is_testnet=True,
def_path=DER_PATH_NON_HARDENED_FULL,
key_net_ver=_BIP86_BTC_KEY_NET_VER_TEST,
wif_net_ver=CoinsConf.BitcoinTestNet.ParamByKey("wif_net_ver"),
bip32_cls=Bip32Slip10Secp256k1,
addr_cls=P2TRAddrEncoder,
addr_params={
"hrp": CoinsConf.BitcoinTestNet.ParamByKey("p2tr_hrp"),
},
)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip86/bip86_conf.py",
"license": "MIT License",
"lines": 74,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/bip86/bip86_conf_getter.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for getting BIP86 coins configuration."""
# Imports
from typing import Dict
from bip_utils.bip.conf.bip86.bip86_coins import Bip86Coins
from bip_utils.bip.conf.bip86.bip86_conf import Bip86Conf
from import BipCoinConf, BipCoins
class Bip86ConfGetterConst:
"""Class container for BIP86 configuration getter constants."""
# Map from Bip86Coins to configuration classes
COIN_TO_CONF: Dict[BipCoins, BipCoinConf] = {
Bip86Coins.BITCOIN: Bip86Conf.BitcoinMainNet,
Bip86Coins.BITCOIN_REGTEST: Bip86Conf.BitcoinRegTest,
Bip86Coins.BITCOIN_TESTNET: Bip86Conf.BitcoinTestNet,
}
class Bip86ConfGetter:
"""
BIP86 configuration getter class.
It allows to get the BIP86 configuration of a specific coin.
"""
@staticmethod
def GetConfig(coin_type: BipCoins) -> BipCoinConf:
"""
Get coin configuration.
Args:
coin_type (BipCoins): Coin type
Returns:
BipCoinConf: Coin configuration
Raises:
TypeError: If coin type is not of a Bip86Coins enumerative
"""
if not isinstance(coin_type, Bip86Coins):
raise TypeError("Coin type is not an enumerative of Bip86Coins")
return Bip86ConfGetterConst.COIN_TO_CONF[coin_type]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/bip86/bip86_conf_getter.py",
"license": "MIT License",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/atom_addr.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for Atom address encoding/decoding."""
# Imports
from typing import Any, Union
from bip_utils.addr.addr_dec_utils import AddrDecUtils
from bip_utils.addr.addr_key_validator import AddrKeyValidator
from bip_utils.addr.iaddr_decoder import IAddrDecoder
from bip_utils.addr.iaddr_encoder import IAddrEncoder
from bip_utils.bech32 import Bech32ChecksumError, Bech32Decoder, Bech32Encoder
from bip_utils.ecc import IPublicKey
from bip_utils.utils.crypto import Hash160
class AtomAddrDecoder(IAddrDecoder):
"""
Atom address decoder class.
It allows the Atom address decoding.
"""
@staticmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode an Algorand address to bytes.
Args:
addr (str): Address string
Other Parameters:
hrp (str): Expected HRP
Returns:
bytes: Public key hash bytes
Raises:
ValueError: If the address encoding is not valid
"""
hrp = kwargs["hrp"]
try:
addr_dec_bytes = Bech32Decoder.Decode(hrp, addr)
except Bech32ChecksumError as ex:
raise ValueError("Invalid bech32 checksum") from ex
AddrDecUtils.ValidateLength(addr_dec_bytes,
Hash160.DigestSize())
return addr_dec_bytes
class AtomAddrEncoder(IAddrEncoder):
"""
Atom address encoder class.
It allows the Atom address encoding.
"""
@staticmethod
def EncodeKey(pub_key: Union[bytes, IPublicKey],
**kwargs: Any) -> str:
"""
Encode a public key to Atom address.
Args:
pub_key (bytes or IPublicKey): Public key bytes or object
Other Parameters:
hrp (str): HRP
Returns:
str: Address string
Raises:
ValueError: If the public key is not valid
TypeError: If the public key is not secp256k1
"""
hrp = kwargs["hrp"]
pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
return Bech32Encoder.Encode(hrp,
Hash160.QuickDigest(pub_key_obj.RawCompressed().ToBytes()))
# Deprecated: only for compatibility, Encoder class shall be used instead
AtomAddr = AtomAddrEncoder
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/atom_addr.py",
"license": "MIT License",
"lines": 82,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/bip_bitcoin_cash_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for Bitcoin Cash configuration handling."""
# Imports
from typing import Any, Dict, Type
from ..addr import IAddrEncoder
from ..bip32 import Bip32KeyNetVersions
from .bip_coin_conf import Bip32Base, BipCoinConf
from ..utils.conf import CoinNames
class BipBitcoinCashConf(BipCoinConf):
"""
Bitcoin Cash configuration class.
It allows to return different addresses depending on the configuration.
"""
m_addr_cls_legacy: Type[IAddrEncoder]
m_use_legacy_addr: bool
def __init__(self, # pylint: disable=too-many-arguments
coin_names: CoinNames,
coin_idx: int,
is_testnet: bool,
def_path: str,
key_net_ver: Bip32KeyNetVersions,
wif_net_ver: bytes,
bip32_cls: Type[Bip32Base],
addr_cls: Type[IAddrEncoder],
addr_cls_legacy: Type[IAddrEncoder],
addr_params: Dict[str, Any]) -> None:
"""
Construct class.
Args:
coin_names (CoinNames object) : Coin names
coin_idx (int) : Coin index
is_testnet (bool) : Test net flag
def_path (str) : Default path
key_net_ver (Bip32KeyNetVersions object): Key net versions
wif_net_ver (bytes) : WIF net version
bip32_cls (Bip32Base class) : Bip32 class
addr_params (dict) : Address parameters
addr_cls (IAddrEncoder class) : Address class
addr_cls_legacy (IAddrEncoder class) : Legacy ddress class
"""
super().__init__(coin_names=coin_names,
coin_idx=coin_idx,
is_testnet=is_testnet,
def_path=def_path,
key_net_ver=key_net_ver,
wif_net_ver=wif_net_ver,
bip32_cls=bip32_cls,
addr_cls=addr_cls,
addr_params=addr_params)
self.m_addr_cls_legacy = addr_cls_legacy
self.m_use_legacy_addr = False
def UseLegacyAddress(self,
value: bool) -> None:
"""
Select if use the legacy address.
Args:
value (bool): True for using legacy address, false for using the standard one
"""
self.m_use_legacy_addr = value
def AddrClass(self) -> Type[IAddrEncoder]:
"""
Get the address type. It overrides the method in BipCoinConf.
Returns:
IAddrEncoder class: Address class
"""
return self.m_addr_cls_legacy if self.m_use_legacy_addr else self.m_addr_cls
def AddrParams(self) -> Dict[str, Any]:
"""
Get the address parameters. It overrides the method in BipCoinConf.
Returns:
dict: Address parameters
"""
return self.m_addr_params["legacy"] if self.m_use_legacy_addr else self.m_addr_params["std"]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/bip_bitcoin_cash_conf.py",
"license": "MIT License",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/bip_coin_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for generic BIP coins configuration handling."""
# Imports
from typing import Any, Dict, Optional, Tuple, Type
from ...addr.iaddr_encoder import IAddrEncoder
from ...bip32 import Bip32Base, Bip32KeyNetVersions, Bip32PublicKey
from ...utils.conf import CoinNames as UtilsCoinNames
class BipCoinFctCallsConf:
"""Bip coin function calls configuration class."""
m_fct_names: Tuple[str, ...]
def __init__(self,
*args: str) -> None:
"""
Construct class.
Args:
args (str): Function names to be called
"""
self.m_fct_names = args
def ResolveCalls(self,
pub_key: Bip32PublicKey) -> Any:
"""
Resolve function calls and get the result.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
Returns:
Any: Result
"""
res = pub_key
for fct_call in self.m_fct_names:
res = getattr(res, fct_call)()
return res
class BipCoinConf: # pylint: disable=too-many-instance-attributes
"""Bip coin configuration class."""
m_coin_names: UtilsCoinNames
m_coin_idx: int
m_is_testnet: bool
m_def_path: str
m_key_net_ver: Bip32KeyNetVersions
m_wif_net_ver: Optional[bytes]
m_bip32_cls: Type[Bip32Base]
m_addr_params: Dict[str, Any]
# m_addr_cls: Type[IAddrEncoder]
m_any_addr_params_fct_call: bool
def __init__(self, # pylint: disable=too-many-arguments
coin_names: UtilsCoinNames,
coin_idx: int,
is_testnet: bool,
def_path: str,
key_net_ver: Bip32KeyNetVersions,
wif_net_ver: Optional[bytes],
bip32_cls: Type[Bip32Base],
# addr_cls: Type[IAddrEncoder],
addr_params: Dict[str, Any]) -> None:
"""
Construct class.
Args:
coin_names (CoinNames object) : Coin names
coin_idx (int) : Coin index
is_testnet (bool) : Test net flag
def_path (str) : Default path
key_net_ver (Bip32KeyNetVersions object): Key net versions
wif_net_ver (bytes) : WIF net version, None if not supported
bip32_cls (Bip32Base class) : Bip32 class
addr_params (dict) : Address parameters
addr_cls (IAddrEncoder class) : Address class
"""
self.m_coin_names = coin_names
self.m_coin_idx = coin_idx
self.m_is_testnet = is_testnet
self.m_def_path = def_path
self.m_key_net_ver = key_net_ver
self.m_wif_net_ver = wif_net_ver
self.m_bip32_cls = bip32_cls
self.m_addr_params = addr_params
self.m_any_addr_params_fct_call = any(
(isinstance(param_val, BipCoinFctCallsConf) for param_val in addr_params.values())
)
# self.m_addr_cls = addr_cls
def CoinNames(self) -> UtilsCoinNames:
"""
Get coin names.
Returns:
CoinNames object: CoinNames object
"""
return self.m_coin_names
def CoinIndex(self) -> int:
"""
Get coin index.
Returns:
int: Coin index
"""
return self.m_coin_idx
def IsTestNet(self) -> bool:
"""
Get if test net.
Returns:
bool: True if test net, false otherwise
"""
return self.m_is_testnet
def DefaultPath(self) -> str:
"""
Get the default derivation path.
Returns:
str: Default derivation path
"""
return self.m_def_path
def KeyNetVersions(self) -> Bip32KeyNetVersions:
"""
Get key net versions.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return self.m_key_net_ver
def WifNetVersion(self) -> Optional[bytes]:
"""
Get WIF net version.
Returns:
bytes: WIF net version bytes
None: If WIF is not supported
"""
return self.m_wif_net_ver
def Bip32Class(self) -> Type[Bip32Base]:
"""
Get the Bip32 class.
Returns:
Bip32Base class: Bip32Base class
"""
return self.m_bip32_cls
def AddrParams(self) -> Dict[str, Any]:
"""
Get the address parameters.
Returns:
dict: Address parameters
"""
return self.m_addr_params
def AddrParamsWithResolvedCalls(self,
pub_key: Bip32PublicKey) -> Dict[str, Any]:
"""
Get the address parameters with resolved function calls.
Args:
pub_key (Bip32PublicKey object): Bip32PublicKey object
Returns:
dict: Address parameters
"""
addr_params = self.AddrParams()
# Just use the internal object if nothing to be resolved to avoid creating a new one
if not self.m_any_addr_params_fct_call:
return addr_params
# Create a new dictionary with resolved function calls
return {
param_name: param_val.ResolveCalls(pub_key) if isinstance(param_val, BipCoinFctCallsConf) else param_val
for param_name, param_val in addr_params.items()
}
# def AddrClass(self) -> Type[IAddrEncoder]:
# """
# Get the address class.
# Returns:
# IAddrEncoder class: Address class
# """
# return self.m_addr_cls
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/bip_coin_conf.py",
"license": "MIT License",
"lines": 178,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/bip_coins.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for generic BIP coins enum."""
# Imports
from enum import Enum
class BipCoins(Enum):
"""Base enum for bip coins."""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/bip_coins.py",
"license": "MIT License",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/bip_conf_const.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for generic BIP configuration constants."""
# Hardened default path (full)
DER_PATH_HARDENED_FULL: str = "0'/0'/0'"
# Hardened default path (mid)
DER_PATH_HARDENED_MID: str = "0'/0'"
# Hardened default path (short)
DER_PATH_HARDENED_SHORT: str = "0'"
# Non-hardened default path (full)
DER_PATH_NON_HARDENED_FULL: str = "0'/0/0"
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/bip_conf_const.py",
"license": "MIT License",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/conf/common/bip_litecoin_conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for Litecoin configuration handling."""
# Imports
from typing import Any, Dict, Type
from bip_utils.addr import IAddrEncoder
from bip_utils.bip.bip32 import Bip32KeyNetVersions
from .bip_coin_conf import Bip32Base, BipCoinConf
from bip_utils.utils.conf import CoinNames
class BipLitecoinConf(BipCoinConf):
"""
Litecoin configuration class.
It allows to return different addresses and key net versions depending on the configuration.
"""
m_alt_key_net_ver: Bip32KeyNetVersions
m_use_alt_key_net_ver: bool
m_use_depr_addr: bool
def __init__(self, # pylint: disable=too-many-arguments
coin_names: CoinNames,
coin_idx: int,
is_testnet: bool,
def_path: str,
key_net_ver: Bip32KeyNetVersions,
alt_key_net_ver: Bip32KeyNetVersions,
wif_net_ver: bytes,
bip32_cls: Type[Bip32Base],
addr_cls: Type[IAddrEncoder],
addr_params: Dict[str, Any]) -> None:
"""
Construct class.
Args:
coin_names (CoinNames object) : Coin names
coin_idx (int) : Coin index
is_testnet (bool) : Test net flag
def_path (str) : Default path
key_net_ver (Bip32KeyNetVersions object) : Key net versions
alt_key_net_ver (Bip32KeyNetVersions object): Key net versions (alternate)
wif_net_ver (bytes) : WIF net version
bip32_cls (Bip32Base class) : Bip32 class
addr_params (dict) : Address parameters
addr_cls (IAddrEncoder class) : Address class
"""
super().__init__(coin_names=coin_names,
coin_idx=coin_idx,
is_testnet=is_testnet,
def_path=def_path,
key_net_ver=key_net_ver,
wif_net_ver=wif_net_ver,
bip32_cls=bip32_cls,
addr_cls=addr_cls,
addr_params=addr_params)
self.m_alt_key_net_ver = alt_key_net_ver
self.m_use_alt_key_net_ver = False
self.m_use_depr_addr = False
def UseAlternateKeyNetVersions(self,
value: bool) -> None:
"""
Select if use the alternate key net version.
Args:
value (bool): True for using alternate key net version, false for using the standard one
"""
self.m_use_alt_key_net_ver = value
def UseDeprecatedAddress(self,
value: bool) -> None:
"""
Select if use the deprecated address.
Args:
value (bool): True for using deprecated address, false for using the standard one
"""
self.m_use_depr_addr = value
def KeyNetVersions(self) -> Bip32KeyNetVersions:
"""
Get key net versions. It overrides the method in BipCoinConf.
Litecoin overrides the method because it can have 2 different key net versions.
Returns:
Bip32KeyNetVersions object: Bip32KeyNetVersions object
"""
return self.m_alt_key_net_ver if self.m_use_alt_key_net_ver else self.m_key_net_ver
def AddrParams(self) -> Dict[str, Any]:
"""
Get the address parameters. It overrides the method in BipCoinConf.
Returns:
dict: Address parameters
"""
return ({"net_ver": self.m_addr_params["depr_net_ver"]}
if self.m_use_depr_addr
else {"net_ver": self.m_addr_params["std_net_ver"]})
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/conf/common/bip_litecoin_conf.py",
"license": "MIT License",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/common/dummy_point.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for representing a dummy point."""
# Imports
from abc import ABC
from typing import Any
from bip_utils.ecc.common.ipoint import IPoint
from bip_utils.utils.misc import BytesUtils, DataBytes, IntegerUtils
class DummyPointConst:
"""Class container for dummy point constants."""
# Point coordinate length in bytes
POINT_COORD_BYTE_LEN: int = 32
class DummyPoint(IPoint, ABC):
"""Dummy point class."""
m_x: int
m_y: int
@classmethod
def FromBytes(cls,
point_bytes: bytes) -> IPoint:
"""
Construct class from point bytes.
Args:
point_bytes (bytes): Point bytes
Returns:
IPoint: IPoint object
"""
return cls(
(
BytesUtils.ToInteger(point_bytes[:DummyPointConst.POINT_COORD_BYTE_LEN]),
BytesUtils.ToInteger(point_bytes[DummyPointConst.POINT_COORD_BYTE_LEN:])
)
)
@classmethod
def FromCoordinates(cls,
x: int,
y: int) -> IPoint:
"""
Construct class from point coordinates.
Args:
x (int): X coordinate of the point
y (int): Y coordinate of the point
Returns:
IPoint: IPoint object
"""
return cls((x, y))
def __init__(self,
point_obj: Any) -> None:
"""
Construct class from point object.
Args:
point_obj (class): Point object
Raises:
TypeError: If point object is not of the correct type
"""
if (not isinstance(point_obj, tuple)
or len(point_obj) != 2
or not isinstance(point_obj[0], int)
or not isinstance(point_obj[1], int)):
raise TypeError("Invalid point object type")
self.m_x = point_obj[0]
self.m_y = point_obj[1]
@staticmethod
def CoordinateLength() -> int:
"""
Get the coordinate length.
Returns:
int: Coordinate key length
"""
return DummyPointConst.POINT_COORD_BYTE_LEN
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
return None
def X(self) -> int:
"""
Get point X coordinate.
Returns:
int: Point X coordinate
"""
return self.m_x
def Y(self) -> int:
"""
Get point Y coordinate.
Returns:
int: Point Y coordinate
"""
return self.m_y
def Raw(self) -> DataBytes:
"""
Return the point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
x_bytes = IntegerUtils.ToBytes(self.m_x, bytes_num=DummyPointConst.POINT_COORD_BYTE_LEN)
y_bytes = IntegerUtils.ToBytes(self.m_y, bytes_num=DummyPointConst.POINT_COORD_BYTE_LEN)
return DataBytes(x_bytes + y_bytes)
def RawEncoded(self) -> DataBytes:
"""
Return the encoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
return self.Raw()
def RawDecoded(self) -> DataBytes:
"""
Return the decoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
return self.Raw()
def __add__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
return self.__class__(
(self.m_x + point.X(), self.m_y + point.Y())
)
def __radd__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
return self.__add__(point)
def __mul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
return self.__class__(
(self.m_x * scalar, self.m_y * scalar)
)
def __rmul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
return self.__mul__(scalar)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/common/dummy_point.py",
"license": "MIT License",
"lines": 174,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/common/ikeys.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with interfaces for public/private keys classes."""
# Imports
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
from .ipoint import IPoint
from ..curve.elliptic_curve_types import EllipticCurveTypes
from ...utils.misc import DataBytes
class IPublicKey(ABC):
"""
Interface for a generic elliptic curve public key.
Verify method is missing because not needed.
"""
@classmethod
@abstractmethod
def FromBytes(cls,
key_bytes: bytes) -> IPublicKey:
"""
Construct class from key bytes.
Args:
key_bytes (bytes): Key bytes
Returns:
IPublicKey: IPublicKey object
Raises:
ValueError: If key bytes are not valid
"""
@classmethod
@abstractmethod
def FromPoint(cls,
key_point: IPoint) -> IPublicKey:
"""
Construct class from key point.
Args:
key_point (IPoint object): Key point
Returns:
IPublicKey: IPublicKey object
Raises:
ValueError: If key point is not valid
"""
@staticmethod
@abstractmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
@classmethod
def IsValidBytes(cls,
key_bytes: bytes) -> bool:
"""
Return if the specified bytes represents a valid public key.
Args:
key_bytes (bytes): Key bytes
Returns:
bool: True if valid, false otherwise
"""
try:
cls.FromBytes(key_bytes)
return True
except ValueError:
return False
@classmethod
def IsValidPoint(cls,
key_point: IPoint) -> bool:
"""
Return if the specified point represents a valid public key.
Args:
key_point (IPoint object): Key point
Returns:
bool: True if valid, false otherwise
"""
try:
cls.FromPoint(key_point)
return True
except ValueError:
return False
@staticmethod
@abstractmethod
def CompressedLength() -> int:
"""
Get the compressed key length.
Returns:
int: Compressed key length
"""
@staticmethod
@abstractmethod
def UncompressedLength() -> int:
"""
Get the uncompressed key length.
Returns:
int: Uncompressed key length
"""
@abstractmethod
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
@abstractmethod
def RawCompressed(self) -> DataBytes:
"""
Return raw compressed public key.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def RawUncompressed(self) -> DataBytes:
"""
Return raw uncompressed public key.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def Point(self) -> IPoint:
"""
Return the public key point.
Returns:
IPoint object: IPoint object
"""
class IPrivateKey(ABC):
"""
Interface for a generic elliptic curve private key.
Sign method is missing because not needed.
"""
@classmethod
@abstractmethod
def FromBytes(cls,
key_bytes: bytes) -> IPrivateKey:
"""
Construct class from key bytes.
Args:
key_bytes (bytes): Key bytes
Returns:
IPrivateKey: IPrivateKey object
Raises:
ValueError: If key bytes are not valid
"""
@staticmethod
@abstractmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
@classmethod
def IsValidBytes(cls,
key_bytes: bytes) -> bool:
"""
Return if the specified bytes represent a valid private key.
Args:
key_bytes (bytes): key bytes
Returns:
bool: True if valid, false otherwise
"""
try:
cls.FromBytes(key_bytes)
return True
except ValueError:
return False
@staticmethod
@abstractmethod
def Length() -> int:
"""
Get the key length.
Returns:
int: Key length
"""
@abstractmethod
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
@abstractmethod
def Raw(self) -> DataBytes:
"""
Return raw private key.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def PublicKey(self) -> IPublicKey:
"""
Get the public key correspondent to the private one.
Returns:
IPublicKey object: IPublicKey object
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/common/ikeys.py",
"license": "MIT License",
"lines": 210,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/common/ipoint.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with interfaces for point classes."""
# Imports
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
from ..curve.elliptic_curve_types import EllipticCurveTypes
from ...utils.misc import DataBytes
class IPoint(ABC):
"""Interface for a generic elliptic curve point."""
@classmethod
@abstractmethod
def FromBytes(cls,
point_bytes: bytes) -> IPoint:
"""
Construct class from point bytes.
Args:
point_bytes (bytes): Point bytes
Returns:
IPoint: IPoint object
"""
@classmethod
@abstractmethod
def FromCoordinates(cls,
x: int,
y: int) -> IPoint:
"""
Construct class from point coordinates.
Args:
x (int): X coordinate of the point
y (int): Y coordinate of the point
Returns:
IPoint: IPoint object
"""
@staticmethod
@abstractmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
@staticmethod
@abstractmethod
def CoordinateLength() -> int:
"""
Get the coordinate length.
Returns:
int: Coordinate key length
"""
@abstractmethod
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
@abstractmethod
def X(self) -> int:
"""
Return X coordinate of the point.
Returns:
int: X coordinate of the point
"""
@abstractmethod
def Y(self) -> int:
"""
Return Y coordinate of the point.
Returns:
int: Y coordinate of the point
"""
@abstractmethod
def Raw(self) -> DataBytes:
"""
Return the point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def RawEncoded(self) -> DataBytes:
"""
Return the encoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def RawDecoded(self) -> DataBytes:
"""
Return the decoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
@abstractmethod
def __add__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
@abstractmethod
def __radd__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
@abstractmethod
def __mul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
@abstractmethod
def __rmul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/common/ipoint.py",
"license": "MIT License",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/conf.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for ECC configuration."""
class EccConf:
"""ECC configuration class."""
# True for using coincurve for secp256k1, false for using ecdsa
USE_COINCURVE: bool = False
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/conf.py",
"license": "MIT License",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for elliptic curves."""
# Imports
from typing import Type
from ..common.ikeys import IPrivateKey, IPublicKey
from ..common.ipoint import IPoint
class EllipticCurve:
"""
Class for a generic elliptic curve.
This is not meant to be complete but just the minimum required to abstract the bip module from
the specific ECC library.
"""
m_name: str
m_order: int
m_generator: IPoint
m_point_cls: Type[IPoint]
m_pub_key_cls: Type[IPublicKey]
m_priv_key_cls: Type[IPrivateKey]
def __init__(self, # pylint: disable=too-many-arguments
name: str,
order: int,
generator: IPoint,
point_cls: Type[IPoint],
pub_key_cls: Type[IPublicKey],
priv_key_cls: Type[IPrivateKey]):
"""
Construct class.
Args:
name (str) : Curve name
order (int) : Curve order
generator (IPoint object) : Curve generator point
point_cls (IPoint class) : Point class
pub_key_cls (IPublicKey class) : Public key class
priv_key_cls (IPrivateKey class): Private key class
"""
self.m_name = name
self.m_order = order
self.m_generator = generator
self.m_point_cls = point_cls
self.m_pub_key_cls = pub_key_cls
self.m_priv_key_cls = priv_key_cls
def Name(self) -> str:
"""
Return the curve name.
Returns:
str: Curve name
"""
return self.m_name
def Order(self) -> int:
"""
Return the curve order.
Returns:
int: Curve order
"""
return self.m_order
def Generator(self) -> IPoint:
"""
Get the curve generator point.
Returns:
IPoint object: IPoint object
"""
return self.m_generator
def PointClass(self) -> Type[IPoint]:
"""
Return the point class.
Returns:
IPoint class: Point class
"""
return self.m_point_cls
def PublicKeyClass(self) -> Type[IPublicKey]:
"""
Return the public key class.
Returns:
IPublicKey class: Public key class
"""
return self.m_pub_key_cls
def PrivateKeyClass(self) -> Type[IPrivateKey]:
"""
Return the private key class.
Returns:
IPrivateKey class: Private key class
"""
return self.m_priv_key_cls
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve.py",
"license": "MIT License",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve_getter.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for getting elliptic curves classes."""
# Imports
from typing import Dict
from .elliptic_curve import EllipticCurve
from .elliptic_curve_types import EllipticCurveTypes
# from ..ed25519.ed25519 import Ed25519
# from ..ed25519_blake2b.ed25519_blake2b import Ed25519Blake2b
# from ..ed25519_kholaw.ed25519_kholaw import Ed25519Kholaw
# from ..ed25519_monero.ed25519_monero import Ed25519Monero
# from ..nist256p1.nist256p1 import Nist256p1
from ..secp256k1.secp256k1 import Secp256k1
# from ..sr25519.sr25519 import Sr25519
class EllipticCurveGetterConst:
"""Class container for elliptic curve getter constants."""
# Elliptic curve type to instance
TYPE_TO_INSTANCE: Dict[EllipticCurveTypes, EllipticCurve] = {
# EllipticCurveTypes.ED25519: Ed25519,
# EllipticCurveTypes.ED25519_BLAKE2B: Ed25519Blake2b,
# EllipticCurveTypes.ED25519_KHOLAW: Ed25519Kholaw,
# EllipticCurveTypes.ED25519_MONERO: Ed25519Monero,
# EllipticCurveTypes.NIST256P1: Nist256p1,
EllipticCurveTypes.SECP256K1: Secp256k1,
# EllipticCurveTypes.SR25519: Sr25519,
}
class EllipticCurveGetter:
"""
Elliptic curve getter class.
It allows to get the elliptic curve class from its type.
"""
@staticmethod
def FromType(curve_type: EllipticCurveTypes) -> EllipticCurve:
"""
Get the elliptic curve class from its type.
Args:
curve_type (EllipticCurveTypes): Curve type
Returns:
EllipticCurve object: EllipticCurve object
Raises:
TypeError: If curve type is not a EllipticCurveTypes enum
"""
if not isinstance(curve_type, EllipticCurveTypes):
raise TypeError("Curve type is not an enumerative of EllipticCurveTypes")
return EllipticCurveGetterConst.TYPE_TO_INSTANCE[curve_type]
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve_getter.py",
"license": "MIT License",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve_types.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for elliptic curves enum."""
# Imports
from enum import Enum, auto, unique
@unique
class EllipticCurveTypes(Enum):
"""Enumerative for elliptic curve types."""
ED25519 = auto()
ED25519_BLAKE2B = auto()
ED25519_KHOLAW = auto()
ED25519_MONERO = auto()
NIST256P1 = auto()
SECP256K1 = auto()
SR25519 = auto()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/curve/elliptic_curve_types.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/ecdsa/ecdsa_keys.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with some ECDSA keys constants."""
class EcdsaKeysConst:
"""Class container for ECDSA keys constants."""
# Point coordinate length in bytes
POINT_COORD_BYTE_LEN: int = 32
# Private key length in bytes
PRIV_KEY_BYTE_LEN: int = 32
# Uncompressed public key prefix
PUB_KEY_UNCOMPRESSED_PREFIX: bytes = b"\x04"
# Compressed public key length in bytes
PUB_KEY_COMPRESSED_BYTE_LEN: int = 33
# Uncompressed public key length in bytes
PUB_KEY_UNCOMPRESSED_BYTE_LEN: int = 65
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/ecdsa/ecdsa_keys.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with secp256k1 curve."""
# Imports
from ..curve.elliptic_curve import EllipticCurve
from .secp256k1_const import (
Secp256k1Const, Secp256k1Point, Secp256k1PrivateKey, Secp256k1PublicKey
)
# Secp256k1 curve definition
Secp256k1: EllipticCurve = EllipticCurve(Secp256k1Const.NAME,
Secp256k1Const.CURVE_ORDER,
Secp256k1Const.GENERATOR,
Secp256k1Point,
Secp256k1PublicKey,
Secp256k1PrivateKey)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_const.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with secp256k1 constants."""
# Imports
from typing import Type
from ..common.ikeys import IPrivateKey, IPublicKey
from ..common.ipoint import IPoint
# Variables
Secp256k1Point: Type[IPoint]
Secp256k1PublicKey: Type[IPublicKey]
Secp256k1PrivateKey: Type[IPrivateKey]
_CURVE_ORDER: int
_GENERATOR: IPoint
from ....ecdsa.ecdsa import generator_secp256k1
from ..secp256k1.secp256k1_keys_ecdsa import (
Secp256k1PointEcdsa, Secp256k1PrivateKeyEcdsa, Secp256k1PublicKeyEcdsa
)
Secp256k1Point = Secp256k1PointEcdsa
Secp256k1PublicKey = Secp256k1PublicKeyEcdsa
Secp256k1PrivateKey = Secp256k1PrivateKeyEcdsa
_CURVE_ORDER = generator_secp256k1.order()
_GENERATOR = Secp256k1Point(generator_secp256k1)
class Secp256k1Const:
"""Class container for Secp256k1 constants."""
# Curve name
NAME: str = "Secp256k1"
# Curve order
CURVE_ORDER: int = _CURVE_ORDER
# Curve generator point
GENERATOR: IPoint = _GENERATOR
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_const.py",
"license": "MIT License",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_keys_ecdsa.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for secp256k1 keys based on ecdsa library."""
# Imports
from typing import Any
from ....ecdsa import curves, ellipticcurve, keys
from ....ecdsa.ecdsa import curve_secp256k1
from ..common.ikeys import IPrivateKey, IPublicKey
from ..common.ipoint import IPoint
from ..curve.elliptic_curve_types import EllipticCurveTypes
from ..ecdsa.ecdsa_keys import EcdsaKeysConst
from .secp256k1_point_ecdsa import Secp256k1PointEcdsa
from ...utils.misc import DataBytes
class Secp256k1PublicKeyEcdsa(IPublicKey):
"""Secp256k1 public key class."""
m_ver_key: keys.VerifyingKey
@classmethod
def FromBytes(cls,
key_bytes: bytes) -> IPublicKey:
"""
Construct class from key bytes.
Args:
key_bytes (bytes): Key bytes
Returns:
IPublicKey: IPublicKey object
Raises:
ValueError: If key bytes are not valid
"""
try:
return cls(keys.VerifyingKey.from_string(key_bytes,
curve=curves.SECP256k1))
except keys.MalformedPointError as ex:
raise ValueError("Invalid public key bytes") from ex
@classmethod
def FromPoint(cls,
key_point: IPoint) -> IPublicKey:
"""
Construct class from key point.
Args:
key_point (IPoint object): Key point
Returns:
IPublicKey: IPublicKey object
Raises:
ValueError: If key point is not valid
"""
try:
return cls(
keys.VerifyingKey.from_public_point(
ellipticcurve.Point(curve_secp256k1,
key_point.X(),
key_point.Y()),
curve=curves.SECP256k1
)
)
except keys.MalformedPointError as ex:
raise ValueError("Invalid public key point") from ex
def __init__(self,
key_obj: keys.VerifyingKey) -> None:
"""
Construct class from key object.
Args:
key_obj (keys.VerifyingKey): Key object
"""
self.m_ver_key = key_obj
@staticmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
return EllipticCurveTypes.SECP256K1
@staticmethod
def CompressedLength() -> int:
"""
Get the compressed key length.
Returns:
int: Compressed key length
"""
return EcdsaKeysConst.PUB_KEY_COMPRESSED_BYTE_LEN
@staticmethod
def UncompressedLength() -> int:
"""
Get the uncompressed key length.
Returns:
int: Uncompressed key length
"""
return EcdsaKeysConst.PUB_KEY_UNCOMPRESSED_BYTE_LEN
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
return self.m_ver_key
def RawCompressed(self) -> DataBytes:
"""
Return raw compressed public key.
Returns:
DataBytes object: DataBytes object
"""
return DataBytes(self.m_ver_key.to_string('compressed'))
def RawUncompressed(self) -> DataBytes:
"""
Return raw uncompressed public key.
Returns:
DataBytes object: DataBytes object
"""
return DataBytes(self.m_ver_key.to_string())
def Point(self) -> IPoint:
"""
Get public key point.
Returns:
IPoint object: IPoint object
"""
return Secp256k1PointEcdsa(self.m_ver_key.pubkey.point)
class Secp256k1PrivateKeyEcdsa(IPrivateKey):
"""Secp256k1 private key class."""
m_sign_key = keys.SigningKey
@classmethod
def FromBytes(cls,
key_bytes: bytes) -> IPrivateKey:
"""
Construct class from key bytes.
Args:
key_bytes (bytes): Key bytes
Returns:
IPrivateKey: IPrivateKey object
Raises:
ValueError: If key bytes are not valid
"""
try:
return cls(keys.SigningKey.from_string(key_bytes,
curve=curves.SECP256k1))
except keys.MalformedPointError as ex:
raise ValueError("Invalid private key bytes") from ex
def __init__(self,
key_obj: keys.SigningKey) -> None:
"""
Construct class from key object.
Args:
key_obj (ecdsa.SigningKey): Key object
"""
self.m_sign_key = key_obj
@staticmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
return EllipticCurveTypes.SECP256K1
@staticmethod
def Length() -> int:
"""
Get the key length.
Returns:
int: Key length
"""
return EcdsaKeysConst.PRIV_KEY_BYTE_LEN
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
return self.m_sign_key
def Raw(self) -> DataBytes:
"""
Return raw private key.
Returns:
DataBytes object: DataBytes object
"""
return DataBytes(self.m_sign_key.to_string())
def PublicKey(self) -> IPublicKey:
"""
Get the public key correspondent to the private one.
Returns:
IPublicKey object: IPublicKey object
"""
return Secp256k1PublicKeyEcdsa(self.m_sign_key.get_verifying_key())
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_keys_ecdsa.py",
"license": "MIT License",
"lines": 198,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_point_ecdsa.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for secp256k1 point based on ecdsa library."""
# Imports
from typing import Any
from ....ecdsa import ellipticcurve, keys
from ....ecdsa.ecdsa import curve_secp256k1
from ..common.ipoint import IPoint
from ..curve.elliptic_curve_types import EllipticCurveTypes
from ..ecdsa.ecdsa_keys import EcdsaKeysConst
from ...utils.misc import BytesUtils, DataBytes, IntegerUtils
class Secp256k1PointEcdsa(IPoint):
"""Secp256k1 point class."""
m_point: ellipticcurve.PointJacobi
@classmethod
def FromBytes(cls,
point_bytes: bytes) -> IPoint:
"""
Construct class from point bytes.
Args:
point_bytes (bytes): Point bytes
Returns:
IPoint: IPoint object
"""
try:
return cls(ellipticcurve.PointJacobi.from_bytes(curve_secp256k1,
point_bytes))
except keys.MalformedPointError as ex:
raise ValueError("Invalid point key bytes") from ex
# ECDSA < 0.17 doesn't have from_bytes method for PointJacobi
except AttributeError:
return cls.FromCoordinates(
BytesUtils.ToInteger(point_bytes[:EcdsaKeysConst.POINT_COORD_BYTE_LEN]),
BytesUtils.ToInteger(point_bytes[EcdsaKeysConst.POINT_COORD_BYTE_LEN:])
)
@classmethod
def FromCoordinates(cls,
x: int,
y: int) -> IPoint:
"""
Construct class from point coordinates.
Args:
x (int): X coordinate of the point
y (int): Y coordinate of the point
Returns:
IPoint: IPoint object
"""
return cls(
ellipticcurve.PointJacobi.from_affine(
ellipticcurve.Point(curve_secp256k1, x, y)
)
)
def __init__(self,
point_obj: ellipticcurve.PointJacobi) -> None:
"""
Construct class from point object.
Args:
point_obj (ellipticcurve.PointJacobi): Point object
"""
self.m_point = point_obj
@staticmethod
def CurveType() -> EllipticCurveTypes:
"""
Get the elliptic curve type.
Returns:
EllipticCurveTypes: Elliptic curve type
"""
return EllipticCurveTypes.SECP256K1
@staticmethod
def CoordinateLength() -> int:
"""
Get the coordinate length.
Returns:
int: Coordinate key length
"""
return EcdsaKeysConst.POINT_COORD_BYTE_LEN
def UnderlyingObject(self) -> Any:
"""
Get the underlying object.
Returns:
Any: Underlying object
"""
return self.m_point
def X(self) -> int:
"""
Get point X coordinate.
Returns:
int: Point X coordinate
"""
return self.m_point.x()
def Y(self) -> int:
"""
Get point Y coordinate.
Returns:
int: Point Y coordinate
"""
return self.m_point.y()
def Raw(self) -> DataBytes:
"""
Return the point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
return self.RawDecoded()
def RawEncoded(self) -> DataBytes:
"""
Return the encoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
try:
return DataBytes(self.m_point.to_bytes("compressed"))
# ECDSA < 0.17 doesn't have to_bytes method for PointJacobi
except AttributeError:
x_bytes = IntegerUtils.ToBytes(self.m_point.x(), EcdsaKeysConst.POINT_COORD_BYTE_LEN)
if self.m_point.y() & 1:
enc_bytes = b"\x03" + x_bytes
else:
enc_bytes = b"\x02" + x_bytes
return DataBytes(enc_bytes)
def RawDecoded(self) -> DataBytes:
"""
Return the decoded point raw bytes.
Returns:
DataBytes object: DataBytes object
"""
try:
return DataBytes(self.m_point.to_bytes())
# ECDSA < 0.17 doesn't have to_bytes method for PointJacobi
except AttributeError:
x_bytes = IntegerUtils.ToBytes(self.m_point.x(), EcdsaKeysConst.POINT_COORD_BYTE_LEN)
y_bytes = IntegerUtils.ToBytes(self.m_point.y(), EcdsaKeysConst.POINT_COORD_BYTE_LEN)
return DataBytes(x_bytes + y_bytes)
def __add__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
return self.__class__(self.m_point + point.UnderlyingObject())
def __radd__(self,
point: IPoint) -> IPoint:
"""
Add point to another point.
Args:
point (IPoint object): IPoint object
Returns:
IPoint object: IPoint object
"""
return self + point
def __mul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
return self.__class__(self.m_point * scalar)
def __rmul__(self,
scalar: int) -> IPoint:
"""
Multiply point by a scalar.
Args:
scalar (int): scalar
Returns:
IPoint object: IPoint object
"""
return self * scalar
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_point_ecdsa.py",
"license": "MIT License",
"lines": 190,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/slip/slip173/slip173.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for SLIP-0173 human-readable parts.
Not all the human-readable parts are defined, but only the used ones.
Reference: https://github.com/satoshilabs/slips/blob/master/slip-0173.md
"""
class Slip173:
"""
SLIP-0173 class.
It defines the human-readable parts in according to SLIP-0173.
"""
AKASH_NETWORK: str = "akash"
AXELAR: str = "axelar"
BAND_PROTOCOL: str = "band"
BINANCE_CHAIN: str = "bnb"
BITCOIN_MAINNET: str = "bc"
BITCOIN_REGTEST: str = "bcrt"
BITCOIN_TESTNET: str = "tb"
CERTIK: str = "certik"
CHIHUAHUA: str = "chihuahua"
CELESTIA: str = "celestia"
COSMOS: str = "cosmos"
DYDX: str = "dydx"
ELROND: str = "erd"
FETCH_AI: str = "fetch"
HARMONY_ONE: str = "one"
INJECTIVE: str = "inj"
IRIS_NETWORK: str = "iaa"
KAVA: str = "kava"
LITECOIN_MAINNET: str = "ltc"
LITECOIN_TESTNET: str = "tltc"
NEUTRON: str = "neutron"
OKEX_CHAIN: str = "ex"
OSMOSIS: str = "osmo"
SECRET_NETWORK: str = "secret"
STAFI: str = "stafi"
TERRA: str = "terra"
ZILLIQA: str = "zil"
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/slip/slip173/slip173.py",
"license": "MIT License",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/slip/slip32/slip32.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for SLIP32 extended key serialization/deserialization.
Reference: https://github.com/satoshilabs/slips/blob/master/slip-0032.md
"""
# Imports
from typing import Tuple, Union
from bip_utils.bech32 import Bech32Decoder, Bech32Encoder
from bip_utils.bip.bip32 import Bip32ChainCode, Bip32Depth, Bip32KeyIndex, Bip32Path, Bip32PathParser
from bip_utils.ecc import IPrivateKey, IPublicKey
from bip_utils.slip.slip32.slip32_key_net_ver import Slip32KeyNetVersions
class Slip32KeySerConst:
"""Class container for SLIP32 key serialize constants."""
# Standard key net versions
STD_KEY_NET_VERSIONS: Slip32KeyNetVersions = Slip32KeyNetVersions("xpub", "xprv")
class _Slip32KeySerializer:
"""
SLIP32 key serializer class.
It serializes private/public keys.
"""
@classmethod
def Serialize(cls,
key_bytes: bytes,
path: Union[str, Bip32Path],
chain_code: Union[bytes, Bip32ChainCode],
key_net_ver_str: str) -> str:
"""
Serialize the specified key bytes.
Args:
key_bytes (bytes) : Key bytes
path (str or Bip32Path object) : BIP32 path
chain_code (bytes or Bip32ChainCode object): Chain code
key_net_ver_str (str) : Key net version string
Returns:
str: Serialized key
"""
if isinstance(path, str):
path = Bip32PathParser.Parse(path)
if isinstance(chain_code, bytes):
chain_code = Bip32ChainCode(chain_code)
# Serialize key
ser_key = (
bytes(Bip32Depth(path.Length())) + cls.__SerializePath(path) + bytes(chain_code) + key_bytes
)
# Encode it
return Bech32Encoder.Encode(key_net_ver_str, ser_key)
@staticmethod
def __SerializePath(path: Bip32Path) -> bytes:
"""
Serialize BIP32 path.
Args:
path (Bip32Path object): BIP32 path
Returns:
bytes: Serialized path
"""
path_bytes = b""
for path_elem in path:
path_bytes += path_elem.ToBytes()
return path_bytes
class Slip32PrivateKeySerializer:
"""
SLIP32 private key serializer class.
It serializes private keys.
"""
@staticmethod
def Serialize(priv_key: IPrivateKey,
path: Union[str, Bip32Path],
chain_code: Union[bytes, Bip32ChainCode],
key_net_ver: Slip32KeyNetVersions = Slip32KeySerConst.STD_KEY_NET_VERSIONS) -> str:
"""
Serialize a private key.
Args:
priv_key (IPrivateKey object) : IPrivateKey object
path (str or Bip32Path object) : BIP32 path
chain_code (bytes or Bip32ChainCode object) : Chain code
key_net_ver (Slip32KeyNetVersions object, optional): Key net versions (SLIP32 net version by default)
Returns:
str: Serialized private key
"""
return _Slip32KeySerializer.Serialize(b"\x00" + priv_key.Raw().ToBytes(),
path,
chain_code,
key_net_ver.Private())
class Slip32PublicKeySerializer:
"""
SLIP32 public key serializer class.
It serializes public keys.
"""
@staticmethod
def Serialize(pub_key: IPublicKey,
path: Union[str, Bip32Path],
chain_code: Union[bytes, Bip32ChainCode],
key_net_ver: Slip32KeyNetVersions = Slip32KeySerConst.STD_KEY_NET_VERSIONS) -> str:
"""
Serialize a public key.
Args:
pub_key (IPublicKey object) : IPublicKey object
path (str or Bip32Path object) : BIP32 path
chain_code (bytes or Bip32ChainCode object) : Chain code
key_net_ver (Slip32KeyNetVersions object, optional): Key net versions (SLIP32 net version by default)
Returns:
str: Serialized public key
"""
return _Slip32KeySerializer.Serialize(pub_key.RawCompressed().ToBytes(),
path,
chain_code,
key_net_ver.Public())
class Slip32DeserializedKey:
"""
SLIP32 deserialized key class.
It represents a key deserialized with the Slip32KeyDeserializer.
"""
m_key_bytes: bytes
m_path: Bip32Path
m_chain_code: Bip32ChainCode
m_is_public: bool
def __init__(self,
key_bytes: bytes,
path: Bip32Path,
chain_code: Bip32ChainCode,
is_public: bool) -> None:
"""
Construct class.
Args:
key_bytes (bytes) : Key bytes
path (Bip32Path object) : BIP32 path
chain_code (Bip32ChainCode object): Chain code
is_public (bool) : True if the key is public, false otherwise
Returns:
str: Serialized public key
"""
self.m_key_bytes = key_bytes
self.m_path = path
self.m_chain_code = chain_code
self.m_is_public = is_public
def KeyBytes(self) -> bytes:
"""
Get key bytes.
Returns:
bytes: Key bytes
"""
return self.m_key_bytes
def Path(self) -> Bip32Path:
"""
Get path.
Returns:
Bip32Path object: Bip32Path object
"""
return self.m_path
def ChainCode(self) -> Bip32ChainCode:
"""
Get chain code.
Returns:
Bip32ChainCode object: Bip32ChainCode object
"""
return self.m_chain_code
def IsPublic(self) -> bool:
"""
Get if public.
Returns:
bool: True if the key is public, false otherwise
"""
return self.m_is_public
class Slip32KeyDeserializer:
"""
SLIP32 key deserializer class.
It deserializes an extended key.
"""
@classmethod
def DeserializeKey(
cls,
ser_key_str: str,
key_net_ver: Slip32KeyNetVersions = Slip32KeySerConst.STD_KEY_NET_VERSIONS
) -> Slip32DeserializedKey:
"""
Deserialize a key.
Args:
ser_key_str (str) : Serialized key string
key_net_ver (Slip32KeyNetVersions object, optional): Key net versions (SLIP32 net version by default)
Returns:
Slip32DeserializedKey object: Slip32DeserializedKey object
Raises:
ValueError: If the key net version is not valid
"""
# Get if key is public/private depending on the net version
is_public = cls.__GetIfPublic(ser_key_str, key_net_ver)
# Decode key
ser_key_bytes = Bech32Decoder.Decode(
key_net_ver.Public() if is_public else key_net_ver.Private(),
ser_key_str
)
# Get parts back
key_bytes, path, chain_code = cls.__GetPartsFromBytes(ser_key_bytes, is_public)
return Slip32DeserializedKey(key_bytes, path, chain_code, is_public)
@staticmethod
def __GetIfPublic(ser_key_str: str,
key_net_ver: Slip32KeyNetVersions) -> bool:
"""
Get if the key is public.
Args:
ser_key_str (str) : Serialized key string
key_net_ver (Slip32KeyNetVersions object): Key net versions
Returns:
bool: True if public, false otherwise
"""
if ser_key_str[:len(key_net_ver.Public())] == key_net_ver.Public():
is_public = True
elif ser_key_str[:len(key_net_ver.Private())] == key_net_ver.Private():
is_public = False
else:
raise ValueError("Invalid extended key (wrong net version)")
return is_public
@staticmethod
def __GetPartsFromBytes(ser_key_bytes: bytes,
is_public: bool) -> Tuple[bytes, Bip32Path, Bip32ChainCode]:
"""
Get back key parts from serialized key bytes.
Args:
ser_key_bytes (bytes): Serialized key bytes
is_public (bool) : True if the key is public, false otherwise
Returns:
Tuple[bytes, Bip32Path, Bip32ChainCode]: key bytes (index 0), BIP32 path (index 1) and chain code (index 2)
"""
depth_idx = 0
path_idx = depth_idx + Bip32Depth.FixedLength()
# Get back depth and path
depth = ser_key_bytes[depth_idx]
path = Bip32Path()
for i in range(depth):
key_index_bytes = ser_key_bytes[path_idx + (i * Bip32KeyIndex.FixedLength()):
path_idx + ((i + 1) * Bip32KeyIndex.FixedLength())]
path = path.AddElem(Bip32KeyIndex.FromBytes(key_index_bytes))
# Get back chain code and key
chain_code_idx = path_idx + (depth * Bip32KeyIndex.FixedLength())
key_idx = chain_code_idx + Bip32ChainCode.FixedLength()
chain_code_bytes = ser_key_bytes[chain_code_idx:key_idx]
key_bytes = ser_key_bytes[key_idx:]
# If private key, the first byte shall be zero and shall be removed
if not is_public:
if key_bytes[0] != 0:
raise ValueError(f"Invalid extended private key (wrong secret: {key_bytes[0]})")
key_bytes = key_bytes[1:]
return key_bytes, path, Bip32ChainCode(chain_code_bytes)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/slip/slip32/slip32.py",
"license": "MIT License",
"lines": 261,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/slip/slip32/slip32_key_net_ver.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for SLIP32 net version class."""
class Slip32KeyNetVersions:
"""
SLIP32 key net versions class.
It represents a SLIP32 key net versions.
"""
m_pub_net_ver: str
m_priv_net_ver: str
def __init__(self,
pub_net_ver: str,
priv_net_ver: str) -> None:
"""
Construct class.
Args:
pub_net_ver (str) : Public net version
priv_net_ver (str): Private net version
"""
self.m_pub_net_ver = pub_net_ver
self.m_priv_net_ver = priv_net_ver
def Public(self) -> str:
"""
Get public net version.
Returns:
str: Public net version
"""
return self.m_pub_net_ver
def Private(self) -> str:
"""
Get private net version.
Returns:
str: Private net version
"""
return self.m_priv_net_ver
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/slip/slip32/slip32_key_net_ver.py",
"license": "MIT License",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/slip/slip44/slip44.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for SLIP-0044 coin types.
Not all the coin types are defined, but only the used ones.
Reference: https://github.com/satoshilabs/slips/blob/master/slip-0044.md
"""
class Slip44:
"""
SLIP-0044 class.
It defines the coin types in according to SLIP-0044.
"""
BITCOIN: int = 0
TESTNET: int = 1
LITECOIN: int = 2
DOGECOIN: int = 3
DASH: int = 5
ETHEREUM: int = 60
ETHEREUM_CLASSIC: int = 61
ICON: int = 74
VERGE: int = 77
ATOM: int = 118
MONERO: int = 128
ZCASH: int = 133
RIPPLE: int = 144
BITCOIN_CASH: int = 145
STELLAR: int = 148
NANO: int = 165
EOS: int = 194
TRON: int = 195
BITCOIN_SV: int = 236
NIMIQ: int = 242
ALGORAND: int = 283
ZILLIQA: int = 313
TERRA: int = 330
POLKADOT: int = 354
NEAR_PROTOCOL: int = 397
ERGO: int = 429
KUSAMA: int = 434
KAVA: int = 459
FILECOIN: int = 461
BAND_PROTOCOL: int = 494
THETA: int = 500
SOLANA: int = 501
ELROND: int = 508
SECRET_NETWORK: int = 529
NINE_CHRONICLES: int = 567
APTOS: int = 637
BINANCE_CHAIN: int = 714
SUI: int = 784
VECHAIN: int = 818
NEO: int = 888
OKEX_CHAIN: int = 996
HARMONY_ONE: int = 1023
ONTOLOGY: int = 1024
TEZOS: int = 1729
CARDANO: int = 1815
AVALANCHE: int = 9000
CELO: int = 52752
PI_NETWORK: int = 314159
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/slip/slip44/slip44.py",
"license": "MIT License",
"lines": 77,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/conf/coin_names.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with helper class for coin names."""
class CoinNames:
"""Helper class for representing coin names."""
m_name: str
m_abbr: str
def __init__(self,
name: str,
abbr: str) -> None:
"""
Construct class.
Args:
name (str): Name
abbr (str): Abbreviation
"""
self.m_name = name
self.m_abbr = abbr
def Name(self) -> str:
"""
Get name.
Returns :
str: Name
"""
return self.m_name
def Abbreviation(self) -> str:
"""
Get abbreviation.
Returns:
str: Abbreviation
"""
return self.m_abbr
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/conf/coin_names.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/aes_ecb.py | # Copyright (c) 2021 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for AES-ECB encryption/decryption."""
#
# Imports
#
from typing import Any, Union
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from ..misc.algo import AlgoUtils
#
# Classes
#
class AesEcbEncrypter:
"""
AES-ECB encrypter class.
It encrypts data using AES-ECB algorithm.
"""
aes: Any
auto_pad: bool
# Constructor
def __init__(self,
key: Union[str, bytes]) -> None:
"""
Construct class.
Args:
key (str or bytes): AES key
"""
self.aes = AES.new(AlgoUtils.Encode(key), AES.MODE_ECB)
self.auto_pad = True
def AutoPad(self,
value: bool) -> None:
"""
Set the auto-pad flag.
Args:
value (bool): Flag value
"""
self.auto_pad = value
def Encrypt(self,
data: Union[str, bytes]) -> bytes:
"""
Encrypt data using AES-ECB algorithm.
Args:
data (str or bytes): Data to be encrypted
Returns:
bytes: Encrypted data
"""
padded_data = self.Pad(data) if self.auto_pad else AlgoUtils.Encode(data)
return self.aes.encrypt(padded_data)
@staticmethod
def Pad(data: Union[str, bytes]) -> bytes:
"""
Pad data using PKCS7 algorithm.
Args:
data (str or bytes): Data to be padded
Returns:
bytes: Padded data
"""
return pad(AlgoUtils.Encode(data), AES.block_size)
class AesEcbDecrypter:
"""
AES-ECB decrypter class.
It decrypts data using AES-ECB algorithm.
"""
aes: Any
def __init__(self,
key: Union[str, bytes]) -> None:
"""
Construct class.
Args:
key (str or bytes): AES key
"""
self.aes = AES.new(AlgoUtils.Encode(key), AES.MODE_ECB)
self.auto_unpad = True
def AutoUnPad(self,
value: bool) -> None:
"""
Set the auto-unpad flag.
Args:
value (bool): Flag value
"""
self.auto_unpad = value
def Decrypt(self,
data: bytes) -> bytes:
"""
Decrypt data using AES-ECB algorithm.
Args:
data (bytes): Data to be decrypted
Returns:
bytes: Decrypted data
"""
dec = self.aes.decrypt(data)
return self.UnPad(dec) if self.auto_unpad else dec
@staticmethod
def UnPad(data: bytes) -> bytes:
"""
Unpad data using PKCS7 algorithm.
Args:
data (bytes): Data to be unpadded
Returns:
bytes: Unpadded data
"""
return unpad(data, AES.block_size)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/aes_ecb.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/blake2.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for BLAKE-2 algorithms."""
# Imports
import hashlib
from abc import ABC, abstractmethod
from typing import Union
from ..misc import AlgoUtils
class Blake2b:
"""
BLAKE2b class.
It computes digests using BLAKE2b algorithm.
"""
@staticmethod
def QuickDigest(data: Union[bytes, str],
digest_size: int,
key: Union[bytes, str] = b"",
salt: Union[bytes, str] = b"") -> bytes:
"""
Compute the digest (quick version).
Args:
data (str or bytes) : Data
digest_size (int) : Digest size
key ((str or bytes, optional) : Key (default: empty)
salt ((str or bytes, optional): Salt (default: empty)
Returns:
bytes: Computed digest
"""
return hashlib.blake2b(AlgoUtils.Encode(data),
digest_size=digest_size,
key=AlgoUtils.Encode(key),
salt=AlgoUtils.Encode(salt)).digest()
class _Blake2bWithSpecificSize(ABC):
"""Abstract class for Blake2b with specific digest size."""
@classmethod
def QuickDigest(cls,
data: Union[bytes, str],
key: Union[bytes, str] = b"",
salt: Union[bytes, str] = b"") -> bytes:
"""
Compute the digest (quick version).
Args:
data (str or bytes) : Data
key (str or bytes, optional) : Key bytes (default: empty)
salt (str or bytes, optional): Salt bytes (default: empty)
Returns:
bytes: Computed digest
"""
return Blake2b.QuickDigest(data, cls.DigestSize(), key, salt)
@staticmethod
@abstractmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
class Blake2b32(_Blake2bWithSpecificSize):
"""
BLAKE2b-32 class.
It computes digests using BLAKE2b-32 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 4
class Blake2b40(_Blake2bWithSpecificSize):
"""
BLAKE2b-40 class.
It computes digests using BLAKE2b-40 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 5
class Blake2b160(_Blake2bWithSpecificSize):
"""
BLAKE2b-160 class.
It computes digests using BLAKE2b-160 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 20
class Blake2b224(_Blake2bWithSpecificSize):
"""
BLAKE2b-224 class.
It computes digests using BLAKE2b-224 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 28
class Blake2b256(_Blake2bWithSpecificSize):
"""
BLAKE2b-256 class.
It computes digests using BLAKE2b-256 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 32
class Blake2b512(_Blake2bWithSpecificSize):
"""
BLAKE2b-512 class.
It computes digests using BLAKE2b-512 algorithm.
"""
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return 64
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/blake2.py",
"license": "MIT License",
"lines": 152,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/chacha20_poly1305.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for ChaCha20-Poly1305 algorithm."""
# Imports
from typing import Tuple, Union
from Crypto.Cipher import ChaCha20_Poly1305
from ..misc import AlgoUtils
class ChaCha20Poly1305:
"""
ChaCha20-Poly1305 class.
It decrypts/encrypts data using ChaCha20-Poly1305 algorithm.
"""
@staticmethod
def Decrypt(key: Union[bytes, str],
nonce: Union[bytes, str],
assoc_data: Union[bytes, str],
cipher_text: Union[bytes, str],
tag: Union[bytes, str]) -> bytes:
"""
Decrypt data.
Args:
key (str or bytes) : Key
nonce (str or bytes) : Nonce
assoc_data (str or bytes): Associated data
cipher_text (bytes) : Cipher text
tag (bytes) : Tag
Returns:
bytes: Decrypted data
"""
cipher = ChaCha20_Poly1305.new(key=AlgoUtils.Encode(key),
nonce=AlgoUtils.Encode(nonce))
cipher.update(AlgoUtils.Encode(assoc_data))
return cipher.decrypt_and_verify(AlgoUtils.Encode(cipher_text), AlgoUtils.Encode(tag))
@staticmethod
def Encrypt(key: Union[bytes, str],
nonce: Union[bytes, str],
assoc_data: Union[bytes, str],
plain_text: Union[bytes, str]) -> Tuple[bytes, bytes]:
"""
Encrypt data.
Args:
key (str or bytes) : Key
nonce (str or bytes) : Nonce
assoc_data (str or bytes): Associated data
plain_text (str or bytes): Plain text
Returns:
tuple[bytes, bytes]: Cipher text bytes (index 0) and tag bytes (index 1)
"""
cipher = ChaCha20_Poly1305.new(key=AlgoUtils.Encode(key),
nonce=AlgoUtils.Encode(nonce))
cipher.update(AlgoUtils.Encode(assoc_data))
return cipher.encrypt_and_digest(AlgoUtils.Encode(plain_text))
@staticmethod
def KeySize() -> int:
"""
Get the key size.
Returns:
int: Key size
"""
return ChaCha20_Poly1305.key_size
@staticmethod
def TagSize() -> int:
"""
Get the tag size.
Returns:
int: Tag size
"""
return 16
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/chacha20_poly1305.py",
"license": "MIT License",
"lines": 85,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/hash160.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for HASH160 algorithm."""
# Imports
from typing import Union
from .ripemd import Ripemd160
from .sha2 import Sha256
class Hash160:
"""
HASH160 class.
It computes digests using HASH160 algorithm.
"""
@staticmethod
def QuickDigest(data: Union[bytes, str]) -> bytes:
"""
Compute the digest (quick version).
Args:
data (str or bytes): Data
Returns:
bytes: Computed digest
"""
return Ripemd160.QuickDigest(Sha256.QuickDigest(data))
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return Ripemd160.DigestSize()
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/hash160.py",
"license": "MIT License",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/hmac.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for SHA-2 algorithms."""
# Imports
import hashlib
import hmac
from typing import Tuple, Union
from ..misc import AlgoUtils
HMAC_USE_DIGEST: bool = hasattr(hmac, "digest")
class HmacSha256:
"""
HMAC-SHA256 class.
It computes digests using HMAC-SHA256 algorithm.
"""
@staticmethod
def QuickDigest(key: Union[bytes, str],
data: Union[bytes, str]) -> bytes:
"""
Compute the digest (quick version).
Args:
key (str or bytes) : Key
data (str or bytes): Data
Returns:
bytes: Computed digest
"""
# Use digest if available
if HMAC_USE_DIGEST:
return hmac.digest(AlgoUtils.Encode(key), AlgoUtils.Encode(data), "sha256")
return hmac.new(AlgoUtils.Encode(key), AlgoUtils.Encode(data), hashlib.sha256).digest()
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return hashlib.sha256().digest_size
class HmacSha512:
"""
HMAC-SHA512 class.
It computes digests using HMAC-SHA512 algorithm.
"""
@staticmethod
def QuickDigest(key: Union[bytes, str],
data: Union[bytes, str]) -> bytes:
"""
Compute the digest (quick version).
Args:
key (str or bytes) : Key
data (str or bytes): Data
Returns:
bytes: Computed digest
"""
# Use digest if available
if HMAC_USE_DIGEST:
return hmac.digest(AlgoUtils.Encode(key), AlgoUtils.Encode(data), "sha512")
return hmac.new(AlgoUtils.Encode(key), AlgoUtils.Encode(data), hashlib.sha512).digest()
@staticmethod
def QuickDigestHalves(key: Union[bytes, str],
data: Union[bytes, str]) -> Tuple[bytes, bytes]:
"""
Compute the digest and return it split into two halves (quick version).
Args:
key (str or bytes) : Key
data (str or bytes): Data
Returns:
tuple[bytes, bytes]: Computed digest left part (index 0) and right part (index 1)
"""
digest_bytes = HmacSha512.QuickDigest(key, data)
return digest_bytes[:HmacSha512.DigestSize() // 2], digest_bytes[HmacSha512.DigestSize() // 2:]
@staticmethod
def DigestSize() -> int:
"""
Get the digest size in bytes.
Returns:
int: Digest size in bytes
"""
return hashlib.sha512().digest_size
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/hmac.py",
"license": "MIT License",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/pbkdf2.py | # Copyright (c) 2022 Emanuele Bellocchia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module for PBKDF2 algorithm."""
# Imports
import hashlib
from typing import Optional, Union
from Crypto.Hash import SHA512
from Crypto.Protocol.KDF import PBKDF2
from ..misc import AlgoUtils
HASHLIB_USE_PBKDF2_SHA512: bool = hasattr(hashlib, "pbkdf2_hmac") # For future changes
class Pbkdf2HmacSha512:
"""
PBKDF2 HMAC-SHA512 class.
It derives keys using PBKDF2 HMAC-SHA512 algorithm.
"""
@staticmethod
def DeriveKey(password: Union[bytes, str],
salt: Union[bytes, str],
itr_num: int,
dklen: Optional[int] = None) -> bytes:
"""
Derive a key.
Args:
password (str or bytes): Password
salt (str or bytes) : Salt
itr_num (int) : Iteration number
dklen (int, optional) : Length of the derived key (default: SHA-512 output length)
Returns:
bytes: Computed result
"""
if HASHLIB_USE_PBKDF2_SHA512:
return hashlib.pbkdf2_hmac("sha512", AlgoUtils.Encode(password), AlgoUtils.Encode(salt), itr_num, dklen)
# Use Cryptodome if not implemented in hashlib
return PBKDF2(AlgoUtils.Encode(password), # type: ignore [arg-type]
AlgoUtils.Encode(salt),
dklen or SHA512.digest_size,
count=itr_num,
hmac_hash_module=SHA512)
| {
"repo_id": "ccxt/ccxt",
"file_path": "python/ccxt/static_dependencies/bip/utils/crypto/pbkdf2.py",
"license": "MIT License",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.