From 92968ee8095fbe32b851d49b117f2fd934a252d9 Mon Sep 17 00:00:00 2001 From: MMDRZA <95309780+Pymmdrza@users.noreply.github.com> Date: Mon, 18 Sep 2023 05:43:47 +0300 Subject: [PATCH] Add files via upload --- cryptofuzz/Wallet.py | 94 +++++++++++++++----------------------------- cryptofuzz/asset.py | 18 +++++++++ cryptofuzz/bs58.py | 2 +- cryptofuzz/tst2.py | 87 +++++++++++++++------------------------- cryptofuzz/utils.py | 76 +++++++++++++++++++++++++++++++---- 5 files changed, 152 insertions(+), 125 deletions(-) create mode 100644 cryptofuzz/asset.py diff --git a/cryptofuzz/Wallet.py b/cryptofuzz/Wallet.py index b8a6460..965c1c0 100644 --- a/cryptofuzz/Wallet.py +++ b/cryptofuzz/Wallet.py @@ -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() diff --git a/cryptofuzz/asset.py b/cryptofuzz/asset.py new file mode 100644 index 0000000..deb6957 --- /dev/null +++ b/cryptofuzz/asset.py @@ -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' diff --git a/cryptofuzz/bs58.py b/cryptofuzz/bs58.py index fb6404f..42dc368 100644 --- a/cryptofuzz/bs58.py +++ b/cryptofuzz/bs58.py @@ -1,7 +1,7 @@ from functools import lru_cache from hashlib import sha256 from typing import Mapping, Union -from assest import ( +from .asset import ( BITCOIN_ALPHABET as ALPHABET, RIPPLE_ALPHABET as XRP_ALPHABET, BASE58_ALPHABET diff --git a/cryptofuzz/tst2.py b/cryptofuzz/tst2.py index 51c375a..f7ea040 100644 --- a/cryptofuzz/tst2.py +++ b/cryptofuzz/tst2.py @@ -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)) diff --git a/cryptofuzz/utils.py b/cryptofuzz/utils.py index 012b0b7..e3ed5bf 100644 --- a/cryptofuzz/utils.py +++ b/cryptofuzz/utils.py @@ -2,14 +2,20 @@ import os, re, hashlib import hmac import random +import struct + import ecdsa from .bs58 import b58encode, b58encode_check, b58decode_check, b58decode, base58_check_encode, base58_encode from mnemonic import Mnemonic -from .assest import ( +from .asset import ( MAIN_DIGEST_RMD160, MAX_PRIVATE_KEY, MAIN_PREFIX, MAIN_SUFFIX, + ZERO_BASE_NET, + VERSION_NETWORK, + BASE58_ALPHABET, + FINGERPRINT_RMD160, COMPRESSED_PREFIX, COMPRESSED_PREFIX2, UNCOMPRESSED_PREFIX, @@ -17,7 +23,7 @@ ) -class Generate: +class Generator: def __init__(self): super().__init__() @@ -38,6 +44,9 @@ def generate_xprv(self) -> str: seed = os.urandom(32) return "xprv" + binascii.hexlify(seed).decode('utf-8') + def generate_binary(self): + return "".join(random.choice("01") for _ in range(256)) + def generate_entropy(self, entropy_bits=256): entropy = os.urandom(entropy_bits // 8) checksum = hashlib.sha256(entropy).digest()[0] @@ -49,19 +58,21 @@ def generate_mnemonic(self, size: int) -> str: return " ".join(random.choices(characters, k=size)).lower() -class Convert: +class Convertor: def __init__(self): super().__init__() - self.gen = Generate() + self.gen = Generator() - def double_sha256(self, data): return hashlib.sha256(hashlib.sha256(data).digest()).digest() + def double_sha256(self, data): + return hashlib.sha256(hashlib.sha256(data).digest()).digest() def mne_to_seed(self, mnemonic, password=""): salt = ("mnemonic" + password).encode('utf-8') seed = hashlib.pbkdf2_hmac('sha512', mnemonic.encode('utf-8'), salt, 2048) return seed[:64] - def hex_to_bytes(self, hexed): return bytes.fromhex(hexed) + def hex_to_bytes(self, hexed): + return bytes.fromhex(hexed) def byte_to_hex(self, seed): privatekey_int = int.from_bytes(hashlib.sha256(seed).digest(), byteorder='big') @@ -113,7 +124,8 @@ def pub_to_hex(self, pubkey, compress=True): return self.pub_to_bytes(pubkey, compress).hex() def byte_to_mne(self, byte: bytes): - return Mnemonic("english").to_mnemonic(byte[:32]) + seed = byte[:32] + return Mnemonic("english").to_mnemonic(seed) def byte_to_wif(self, private_key, compress=True): PREFIX = MAIN_PREFIX @@ -129,6 +141,38 @@ def byte_to_wif(self, private_key, compress=True): return WIF.decode('utf-8') + def base58encode(self, 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) + + def base58encodeCheck(self, prefix, payload): + s = prefix + payload + raw = hashlib.sha256(hashlib.sha256(s).digest()).digest()[:4] + return self.base58encode(int.from_bytes(s + raw, 'big')) + + def byte_to_xprv(self, byte_code: bytes) -> str: + chain_code = bytes.fromhex(ZERO_BASE_NET) + child_number = struct.pack('>L', 0) # child number for main key + key = MAIN_DIGEST_RMD160 + byte_code # 0x00 + private key + + xprv_main = VERSION_NETWORK + MAIN_DIGEST_RMD160 + FINGERPRINT_RMD160 + child_number + chain_code + key + decode_main = self.base58encodeCheck(b"", xprv_main) + return "xprv" + decode_main + + def byte_to_addr(self, seedBytes, compress=False): + _, pub = self.byte_to_keys(seedBytes) + if compress: + return self.pub_to_addr(pub, True) + else: + return self.pub_to_addr(pub, False) + def pass_To_addr(self, passphrase, compress=False): priv_key_hex = hashlib.sha256(passphrase.encode()).hexdigest() sk = ecdsa.SigningKey.from_string(bytes.fromhex(priv_key_hex), curve=ecdsa.SECP256k1) @@ -147,6 +191,7 @@ def pass_To_addr(self, passphrase, compress=False): address = base58_check_encode(ripemd160.digest()) return "1" + address + def xprv_to_bytes(self, xprv): return binascii.unhexlify(xprv[4:])[:32] @@ -158,4 +203,21 @@ def xprv_to_addr(self, xprv, compress: bool = False): else: return self.pub_to_addr(pub, False) + def xprv_to_pub(self, xprv, compress: bool = False): + seed = self.xprv_to_bytes(xprv) + pub = self.bytes_to_pub(seed) + if compress: + return self.pub_to_addr(pub, True) + else: + return self.pub_to_addr(pub, False) + def xprv_to_wif(self, xprv, compress: bool = False): + seed = self.xprv_to_bytes(xprv) + if compress: + return self.byte_to_wif(seed, True) + else: + return self.byte_to_wif(seed, False) + + def xprv_to_mne(self, xprv): + seed = self.xprv_to_bytes(xprv) + return self.byte_to_mne(seed)