forked from Pymmdrza/cryptoFuzz
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
152 additions
and
125 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,91 +1,61 @@ | ||
import os, random | ||
import utils | ||
# programmer and owner mmdrza.com | ||
|
||
from . import Convertor, Generator | ||
|
||
def getPrivateKey(): return utils.generate_private_key() | ||
|
||
def getPrivateKey(): | ||
return Generator.generate_private_key() | ||
|
||
def getByte(size: int = 32) -> bytes: return os.urandom(size) | ||
|
||
def getMnemonic(size: int = 12) -> str: | ||
return Generator.generate_mnemonic(size) | ||
|
||
def getMnemonic(size: int) -> str: | ||
if size: | ||
return utils.generate_mnemonic(size) | ||
else: | ||
return utils.generate_mnemonic(size=12) | ||
|
||
|
||
def getRootKey(): return utils.generate_xprv() | ||
|
||
|
||
def getBinary(): | ||
bin_data = [''.join(random.choices('01', k=8)) for _ in range(32)] | ||
return ''.join(bin_data) | ||
|
||
def getBinary() -> str: | ||
return Generator.generate_binary() | ||
|
||
def getEntropy(size: int = 256) -> bytes: | ||
return utils.generate_entropy(size) | ||
|
||
|
||
def getChecksum(data: bytes) -> bytes: | ||
return utils.SHA256(data).digest()[:4] | ||
|
||
|
||
def PrivateKey_To_Addr(private_key: str, compress: bool = False) -> str: | ||
seed = utils.hex_to_bytes(private_key) | ||
priv, pub = utils.byte_to_keys(seed) | ||
if compress: | ||
return utils.pub_to_addr(pub, True) | ||
else: | ||
return utils.pub_to_addr(pub, False) | ||
def getRootKey() -> str: | ||
return Generator.generate_xprv() | ||
|
||
|
||
def PrivateKey_To_WIF(private_key: str, compress: bool = False) -> str: | ||
seed = utils.hex_to_bytes(private_key) | ||
priv, pub = utils.byte_to_keys(seed) | ||
def PrivateKey_To_Addr(hexed: str, compress: bool = False) -> str: | ||
seed = Convertor.hex_to_bytes(hexed) | ||
if compress: | ||
return utils.byte_to_wif(priv, True) | ||
return Convertor.byte_to_addr(seed, True) | ||
else: | ||
return utils.byte_to_wif(priv, False) | ||
return Convertor.byte_to_addr(seed, False) | ||
|
||
|
||
def Mnemonic_To_Addr(mnemonic: str, password: str = "", compress: bool = False) -> str: | ||
seed = utils.mne_to_seed(mnemonic, password) | ||
priv, pub = utils.byte_to_keys(seed) | ||
def PrivateKey_To_Wif(hexed: str, compress: bool = False) -> str: | ||
seed = Convertor.hex_to_bytes(hexed) | ||
if compress: | ||
return utils.pub_to_addr(pub, True) | ||
return Convertor.byte_to_wif(seed, True) | ||
else: | ||
return utils.pub_to_addr(pub, False) | ||
return Convertor.byte_to_wif(seed, False) | ||
|
||
|
||
def Bytes_To_PrivateKey(data: bytes) -> str: return utils.byte_to_hex(data) | ||
|
||
|
||
def Bytes_To_WIF(data: bytes, compress: bool = False) -> str: | ||
if compress: | ||
return utils.byte_to_wif(data, True) | ||
else: | ||
return utils.byte_to_wif(data, False) | ||
|
||
def PrivateKey_To_PublicKey(hexed: str) -> str: | ||
seed = Convertor.hex_to_bytes(hexed) | ||
pub = Convertor.bytes_to_pub(seed) | ||
return pub.hex() | ||
|
||
def Bytes_To_Mnemonic(data: bytes) -> str: return utils.byte_to_mne(data) | ||
|
||
def PrivateKey_To_Mnemonic(hexed: str) -> str: | ||
seed = Convertor.hex_to_bytes(hexed) | ||
return Convertor.byte_to_mne(seed[:32]) | ||
|
||
def Bytes_To_Dec(data: bytes) -> int: return int.from_bytes(data, byteorder='big') | ||
|
||
def PrivateKey_To_Byte(hexed: str) -> bytes: | ||
return Convertor.hex_to_bytes(hexed) | ||
|
||
def Bytes_To_Hex(data: bytes) -> str: return data.hex() | ||
|
||
def PrivateKey_To_Binary(hexed: str): | ||
seed = Convertor.hex_to_bytes(hexed) | ||
chunks = [bin_str[i:i + 8] for i in range(0, len(bin_str), 8)] | ||
|
||
def Bytes_To_Addr(data: bytes, compress: bool = False) -> str: | ||
pvk, pub = utils.byte_to_keys(data) | ||
if compress: | ||
return utils.pub_to_addr(pub, True) | ||
else: | ||
return utils.pub_to_addr(pub, False) | ||
# Convert each chunk into a byte and concatenate | ||
return bytes([int(chunk, 2) for chunk in chunks]) | ||
|
||
|
||
def Bytes_To_PublicKey(data: bytes) -> str: | ||
_, pub = utils.byte_to_keys(data) | ||
return pub.hex() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# script | ||
|
||
BITCOIN_ALPHABET = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | ||
RIPPLE_ALPHABET = b'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz' | ||
BIP39 = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo" | ||
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | ||
ZERO_BASE_NET = "0000000000000000000000000000000000000000000000000000000000000000" | ||
|
||
# main | ||
MAIN_PREFIX = b'\x80' | ||
MAIN_SUFFIX = b'\x01' | ||
COMPRESSED_PREFIX = b'\x03' | ||
COMPRESSED_PREFIX2 = b'\x02' | ||
UNCOMPRESSED_PREFIX = b'\x04' | ||
MAIN_DIGEST_RMD160 = b"\x00" | ||
MAX_PRIVATE_KEY = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 | ||
VERSION_NETWORK = b'\x04\x88\xAD\xE4' | ||
FINGERPRINT_RMD160 = b'\x00\x00\x00\x00' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,44 @@ | ||
import os | ||
import binascii | ||
import ecdsa | ||
import hashlib | ||
import base58 | ||
|
||
|
||
def generate_xprv(): | ||
seed = os.urandom(64) | ||
return "xprv" + binascii.hexlify(seed).decode('utf-8') | ||
|
||
|
||
def xprv_to_private_key(xprv): | ||
return binascii.unhexlify(xprv[4:])[:32] # Take the first 32 bytes as the private key | ||
|
||
|
||
def double_sha256(data): | ||
return hashlib.sha256(hashlib.sha256(data).digest()).digest() | ||
|
||
|
||
def ripemd160(data): | ||
h = hashlib.new('ripemd160') | ||
h.update(data) | ||
return h.digest() | ||
|
||
|
||
def private_key_to_public_key(private_key): | ||
sk = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1) | ||
return sk.get_verifying_key() | ||
|
||
import struct | ||
import binascii | ||
|
||
def public_key_to_address(pubkey, compressed=True): | ||
# Get x and y coordinates from the public key | ||
x = pubkey.pubkey.point.x() | ||
y = pubkey.pubkey.point.y() | ||
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | ||
|
||
if compressed: | ||
if y & 1: | ||
pubkey_bytes = b'\x03' + x.to_bytes(32, 'big') | ||
else: | ||
pubkey_bytes = b'\x02' + x.to_bytes(32, 'big') | ||
else: | ||
pubkey_bytes = b'\x04' + x.to_bytes(32, 'big') + y.to_bytes(32, 'big') | ||
|
||
hashed_pubkey = ripemd160(double_sha256(pubkey_bytes)) | ||
address_bytes = b'\x00' + hashed_pubkey | ||
checksum = double_sha256(address_bytes)[:4] | ||
def base58encode(num): | ||
"""Encode a number using Base58.""" | ||
if num == 0: | ||
return BASE58_ALPHABET[0] | ||
arr = [] | ||
while num: | ||
num, rem = divmod(num, 58) | ||
arr.append(BASE58_ALPHABET[rem]) | ||
arr.reverse() | ||
return ''.join(arr) | ||
|
||
return base58.b58encode(address_bytes + checksum).decode('utf-8') | ||
|
||
def base58encodeCheck(prefix, payload): | ||
"""Encode a byte string using Base58 with a 4-byte checksum.""" | ||
s = prefix + payload | ||
raw = hashlib.sha256(hashlib.sha256(s).digest()).digest()[:4] | ||
return base58encode(int.from_bytes(s + raw, 'big')) | ||
|
||
def main(): | ||
xprv = generate_xprv() | ||
print("XPRV:", xprv) | ||
|
||
private_key = xprv_to_private_key(xprv) | ||
public_key = private_key_to_public_key(private_key) | ||
def byte_to_xprv(byte_code): | ||
# Default chain code | ||
chain_code = bytes.fromhex("0000000000000000000000000000000000000000000000000000000000000000") | ||
# Main map xprv | ||
xprv_version = b'\x04\x88\xAD\xE4' # for bitcoin version | ||
depth = b'\x00' # zero depth | ||
parent_fingerprint = b'\x00\x00\x00\x00' # main key | ||
child_number = struct.pack('>L', 0) # child number for main key | ||
key = b'\x00' + byte_code # 0x00 + private key | ||
|
||
compressed_address = public_key_to_address(public_key, compressed=True) | ||
uncompressed_address = public_key_to_address(public_key, compressed=False) | ||
xprv_main = xprv_version + depth + parent_fingerprint + child_number + chain_code + key | ||
|
||
print("Compressed Address:", compressed_address) | ||
print("Uncompressed Address:", uncompressed_address) | ||
return base58encodeCheck(b"", xprv_main) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() | ||
# Test | ||
byte_code = binascii.unhexlify("c37c299bb6d7ab2c9a2e6da66e9b69404b25bb209e377e9f6a37f1f3e7c2928c") | ||
print(byte_to_xprv(byte_code)) |
Oops, something went wrong.