Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Pymmdrza authored Sep 15, 2023
1 parent fd9d39d commit 922cb35
Show file tree
Hide file tree
Showing 8 changed files with 418 additions and 31 deletions.
91 changes: 91 additions & 0 deletions cryptofuzz/Wallet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import os, random
import utils


def getPrivateKey(): return utils.generate_private_key()


def getByte(size: int = 32) -> bytes: return os.urandom(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 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 PrivateKey_To_WIF(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.byte_to_wif(priv, True)
else:
return utils.byte_to_wif(priv, 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)
if compress:
return utils.pub_to_addr(pub, True)
else:
return utils.pub_to_addr(pub, 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 Bytes_To_Mnemonic(data: bytes) -> str: return utils.byte_to_mne(data)


def Bytes_To_Dec(data: bytes) -> int: return int.from_bytes(data, byteorder='big')


def Bytes_To_Hex(data: bytes) -> str: return data.hex()


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)


def Bytes_To_PublicKey(data: bytes) -> str:
_, pub = utils.byte_to_keys(data)
return pub.hex()

6 changes: 4 additions & 2 deletions cryptofuzz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@
"__description__",
"assest",
"bs58",
"utils"
]
"utils",
"hd",
"Wallet"
]
5 changes: 5 additions & 0 deletions cryptofuzz/assest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
BITCOIN_ALPHABET = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
RIPPLE_ALPHABET = b'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'
BIP39 = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo"
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

# 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
17 changes: 16 additions & 1 deletion cryptofuzz/bs58.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from typing import Mapping, Union
from assest import (
BITCOIN_ALPHABET as ALPHABET,
RIPPLE_ALPHABET as XRP_ALPHABET
RIPPLE_ALPHABET as XRP_ALPHABET,
BASE58_ALPHABET
)


Expand Down Expand Up @@ -134,3 +135,17 @@ def b58decode_check(
raise ValueError("Invalid checksum")

return result


def base58_encode(num):
num = int(num, 16)
encoded = ''
while num:
num, remainder = divmod(num, 58)
encoded = BASE58_ALPHABET[remainder] + encoded
return encoded

def base58_check_encode(payload, prefix=0x00):
payload = bytes([prefix]) + payload
checksum = sha256(sha256(payload).digest()).digest()[:4]
return base58_encode(payload.hex() + checksum.hex())
103 changes: 103 additions & 0 deletions cryptofuzz/hd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import sys

from hdwallet import HDWallet
from hdwallet.symbols import BTC, ETH, LTC, TRX, DASH, DGB, BTG, DOGE, RVN, QTUM


def hex2eth(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=ETH)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2trx(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=TRX)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2ltc(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=LTC)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2dash(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=DASH)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2btg(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=BTG)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2dgb(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=DGB)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2doge(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=DOGE)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2rvn(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=RVN)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2qtum(pvk: str) -> str:
hd: HDWallet = HDWallet(symbol=QTUM)
hd.from_private_key(private_key=pvk)
return hd.p2pkh_address()


def hex2btc(pvk: str, type: str) -> str:
"""
Convert a given hexadecimal private key to a Bitcoin address of the specified type.
Args:
pvk (str): The hexadecimal private key.
type (str): The type of Bitcoin address to generate.
Possible values are "p2pkh", "p2sh", "p2wpkh", "p2wsh", "p2wpkh-p2sh", "p2wsh-p2sh".
Returns:
str: The Bitcoin address corresponding to the private key and address type.
Raises:
None
Example:
>>> hex2btc("0123456789abcdef", "p2pkh")
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
>>> hex2btc("0123456789abcdef", "p2sh")
"3FZbgi29cpjq2GjdwV8eyHuJJnkLtktZc5"
Note:
Make sure that the private key is a valid hexadecimal string.
"""
hd: HDWallet = HDWallet(symbol=BTC)
hd.from_private_key(private_key=pvk)
if type == "p2pkh":
return hd.p2pkh_address()
elif type == "p2sh":
return hd.p2sh_address()
elif type == "p2wpkh":
return hd.p2wpkh_address()
elif type == "p2wsh":
return hd.p2wsh_address()
elif type == "p2wpkh-p2sh":
return hd.p2wpkh_in_p2sh_address()
elif type == "p2wsh-p2sh":
return hd.p2wsh_in_p2sh_address()
else:
err = f"Invalid address type: {type} not supported. Supported types are: p2pkh | p2sh | p2wpkh | p2wsh | p2wpkh-p2sh | p2wsh-p2sh"
sys.stdout.write(err)

20 changes: 20 additions & 0 deletions cryptofuzz/tst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from utils import *

import os


pvk = os.urandom(32).hex()

seed = hex_to_bytes(pvk)

pub = bytes_to_pub(seed)

caddr = pub_to_addr(pub, True)
uaddr = pub_to_addr(pub, False)

print(f"Private Key: {pvk}")
print(f"Seed: {seed}")
print(f"Public Key: {pub}")
print(f"Compressed Address: {caddr}")
print(f"Uncompressed Address: {uaddr}")

67 changes: 67 additions & 0 deletions cryptofuzz/tst2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
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()


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()

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]

return base58.b58encode(address_bytes + checksum).decode('utf-8')


def main():
xprv = generate_xprv()
print("XPRV:", xprv)

private_key = xprv_to_private_key(xprv)
public_key = private_key_to_public_key(private_key)

compressed_address = public_key_to_address(public_key, compressed=True)
uncompressed_address = public_key_to_address(public_key, compressed=False)

print("Compressed Address:", compressed_address)
print("Uncompressed Address:", uncompressed_address)


if __name__ == "__main__":
main()
Loading

0 comments on commit 922cb35

Please sign in to comment.